Convert Decimal to Binary using Recursion Java

Go To StackoverFlow.com

0

I am trying to simply convert to Binary with recursion. I am having problems with the return statement. This compiles but give an overflow error when run. I don't know what to return (or if my statement is wrong) to prevent this error.

Thanks!

public static String convertToBinary(int number)
{
  if(number > 0)
    {
      convertToBinary(number / 2);
      convertToBinary((number % 2 ));
     }

   return convertToBinary((number));
}
2012-04-05 18:01
by user1315954
Is this homework? (assuming it is) please tag it as such - James Montagne 2012-04-05 18:04
You need a base case. This just runs forever (or, tries to until it hits an overflow) - trutheality 2012-04-05 18:06
@trutheality Regardless of having a base case or not, the final line calls itself with the same arguments, so nothing changes in the next level down - Izkata 2012-04-05 18:09
@Izkata That too. Right now it doesn't even get there - trutheality 2012-04-05 18:12
You already have binary. int number is already binary. Your question doesn't make sense - user207421 2017-02-14 22:38


5

Your problem was calling convertToBinary on both number/2 and number%2 I believe. This code works fine for me and isn't that different from what you had:

import java.util.Scanner;

public class DecToBin {

public static void main(String[] args) {

    int input;
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter number to convert to binary: ");
    input = scan.nextInt();
    convert(input);

}

public static void convert(int num) {
    if (num>0) {
        convert(num/2);
        System.out.print(num%2 + " ");
    }
}

}
2012-04-05 18:09
by Chris
Although this code is recursive, it probably isn't what was required, assuming that indeed this was a homework - biziclop 2012-04-05 18:10


4

Well, the problem seems to be that you're not actually doing anything in your recursive method.

In its most basic form your recursive method should contain:

  1. One or more escape conditions.
  2. Recursive calls to itself.

(This is an oversimplified view, but it will do for now.)

The problem is that you're missing some escape conditions to handle the case of the parameter being a single bit long, that is when you can't subdivide it any more.

The other problem with your code is that you're not doing anything with the result of the recursive calls. You should store and concatenate them.

I suggest you start again: write a method that converts a single bit first (this will be non-recursive), then add the recursion to it. (A general advice: don't be afraid to throw away code and start again from scratch.)

2012-04-05 18:06
by biziclop


3

Assuming this is homework I'll point out the main error..

return convertToBinary((number));

The return should return a value, not call a function. This will just adding a recursive state stacks which leads to your overflow. Try saving the values from your previous calls into a variable and returning that.

2012-04-05 18:06
by RyanS


2



1

Once number reaches zero, the method will simply call itself over and over again. The final return needs to return something else - like a string. Having said that, I don't think this approach is terribly optimal.

2012-04-05 18:06
by Rory Hunter
Even worse, it is always calling itself over and over again, no matter what the value of number is - Jesper 2012-04-05 18:09


1

Try below -:

public static String dec2Bin(int num) {
    String result = ((num % 2 == 0) ? "0" : "1"); // expr

    if (abs(num) > 1) {
        result = dec2Bin(num / 2) + result;
    }

    return result;
}
2017-06-29 04:36
by user1658283


0

This works but you have to print it from end

static void printBinary(int x){
     if(x==0)System.out.printf("%3d", x);
      else{
           System.out.printf("%3d",x%2);
           printBinary(x/2);
      }
}
2017-02-04 23:27
by Bikky Kumar


0

Following will work recursively. If number is negative it will add "-" as prefix to result.

    void printBinary (int n) {
            if (n < 0) {         //base case
                System.out.print("-");
                printBinary(-n);
            } else if (n < 2) {    //base case
                System.out.print(n);
                return;
            } else {
                printBinary(n/2);   //recursive step
                int answer = n%2;   
                System.out.print(answer);
            }

        }
2017-10-27 10:47
by i.AsifNoor


0

class DecBin {
    static int convert(int i) {
        if (i > 0) {
            convert (i/2);
            System.out.println(i%2);
            return 0;
        } else {
            return 0;
        }
     }

    public static void main(String[]  args) {
        DecBin.convert(10);
    }
}
2017-11-17 13:18
by Benny isaac


-1

I tried to create a generic sub-routine which takes any Decimal integer & convert it to required BASE.

private Integer convertToBaseN(int num,int n, int pow)
{
    Integer r = num%n;

    if(num < n)
        return new Double((Math.pow(10, pow-1))*r.doubleValue()).intValue();

    return convertToBaseN(num/n, n,pow+1)+ 
            new Double(Math.pow(10, pow-1)*r.doubleValue()).intValue();
}

    num :- Decimal No you want to convert.
    n:- Base to which you want to convert ( n =2 in your case).
    pow = 1 (fixed);


    Input=> convertToBaseN(503,5, 1); Output=> 4003
    Input=> convertToBaseN(7,2, 1); Output=> 111

Caution:- It will not work for negative numbers.

2015-06-24 04:40
by Aiden
There is no decimal integer here - user207421 2017-02-14 22:48


-1

Just add the binary conversion of (number/2*10) to the remainder of the number:

int binary(int dec) {
    int remainder=dec%2;

    if (dec==1 || dec==0)
        return dec;
    else
        return remainder + (binary(dec/2)*10);
}
2016-06-06 00:44
by Faiq arif


-1

public class DecImalToBinary {
    public static String decimalToBinary(int num){
        StringBuilder sb= new StringBuilder();
        if (num <2){
            return ""+ num;
        }
        else{
            return (sb.append(num%2)) + decimalToBinary((num/2));           
        }
    }

    public static void main(String[] args){
        System.out.println(decimalToBinary(8));
    }
}
2016-06-08 13:46
by Esehak Hussen
Could you supply more information in your answer about what is happening in the code to answer the question - Gary Evans 2016-06-08 13:56


-1

public String convertirABinario(int n){
    String b = "";
    if (n == 0 || n == 1){
      b = "" + n;
    }
    else{
      b = b + convertirABinario(n/2) + n%2;
    }
    return b;
}
2016-11-26 04:54
by Julián Rodríguez Brenes
Welcome to StackOverflow Julian. Could you please refine your code snippet for readability? Also, please provide some descriptive context, as to why you think this is a solution to the question. For help, see How to Write a Good Answer on StackOverflow - jacefarm 2016-11-26 05:04


-1

Here is my solution:

 public static String binaerRec(int number)
{
    if (number > 1)
    {
        return binaerRec(number / 2) + number % 2;
    } else
    {
        return 1 + "";
    }
}

have fun

2017-02-14 22:35
by markus
Integer.parseInt() already does the decimal to binary conversion. The rest of it is just a waste of time. However credit for being about the only answer so far that recognizes that the input can't be an int - user207421 2017-02-14 22:48
Ads