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));
}
5
  • 2
    Is this homework? (assuming it is) please tag it as such. Commented Apr 5, 2012 at 18:04
  • You need a base case. This just runs forever (or, tries to until it hits an overflow). Commented Apr 5, 2012 at 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. Commented Apr 5, 2012 at 18:09
  • @Izkata That too. Right now it doesn't even get there. Commented Apr 5, 2012 at 18:12
  • You already have binary. int number is already binary. Your question doesn't make sense. Commented Feb 14, 2017 at 22:38

15 Answers 15

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 + " ");
    }
}

}
Sign up to request clarification or add additional context in comments.

1 Comment

Although this code is recursive, it probably isn't what was required, assuming that indeed this was a homework.
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.)

Comments

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.

Comments

2

If this is not for homework, consider either: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29

or

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29

Comments

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.

1 Comment

Even worse, it is always calling itself over and over again, no matter what the value of number is.
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;
}

Comments

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);
      }
}

Comments

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);
            }

        }

Comments

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);
    }
}

Comments

0
class Example{
    public static String binary(int num){
        String b = " "; // create empty string to concat the binary values
        if (num == 0) {
            return "0"; // return 0 for decimel 0
        } else if(num == 1) {
            return "1"; // return 1 for decimel 1
        } else {
            return b + binary(num/2)+(num%2);
        }
    }
    
    public static void main(String args[]){
        System.out.println(binary(128));    //print 10000000
        System.out.println(binary(64));     //print 1000000
        System.out.println(binary(1));      //print 1
        System.out.println(binary(0));      //print 0
    }
}

Comments

-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.

1 Comment

There is no decimal integer here.
-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);
}

Comments

-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));
    }
}

1 Comment

Could you supply more information in your answer about what is happening in the code to answer the question.
-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;
}

1 Comment

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.
-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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.