1

The following code works when I just want to print the digits out instead of saving them in a String variable:

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

However, what I'm trying to do is to append each binary digit to the end of a String. The method I have to do this is:

public static String toBinary(int num){
    String binary = "";

    if(num > 0){
      toBinary(num/2);
      binary += (num%2);
    }
    return binary;
  }

Regardless of the number passed in for this method, the String ends up being a single 1 or 0. I thought that the logic would be the same, which apparently is wrong. Any help?

2
  • Why not to user Integer.toBinaryString(int)? Commented Apr 23, 2016 at 15:12
  • Note that both versions fail for a 0 value and for any negative number. Commented Apr 23, 2016 at 15:26

2 Answers 2

1

Assign return value of toBinary() method to binary variable :

if(num > 0){
  binary = toBinary(num/2);
  binary += (num%2);
}

Note: Generation of binary string is very easy in Java e.g.

System.out.println(Integer.toBinaryString(23));

Output:

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

4 Comments

You got my +1, but would you like to teach the class how to make it work for a 0 value and for negative numbers? Hint: It requires a driver method and uses bit-shifting instead of division.
@Andreas Thanks for your +1. I would not implement my own toBinaryString() method rather go with buitin java method. If we see the implementation of Integer.toBinaryString(): unsigned right shift operator ">>>" used to divide by 2 (i >>>= shift;) , use 32 bit buffer to hold result and digits an array to get 0 or 1 (deciding ODD or EVEN [i & mask]). So far, to be clear about this method we need to know bitwise oprators well.
Note the name of the person asking the question: ConfusedStudent. This is about learning to code. Calling a library method to do it for you is not the point of the exercise. But you are right, the student may not have learned bit-manipulation yet.
Definitely, It's a big advantage to know the implementation of buitl-in method. And a try to implement own implementation opens learning new things. But personally I like to use existing methods in my work which is already optimized and most of the its very difficult for me to write better than that.
1

The problem with your attempt at recursion is that you are initialising the binary variable at every level and so you don't get the full result of the recursion. You will only ever get the last digit. It will get passed back up the recurse chain at the very end.

The recursive equivalent of your original method would be something like the following:

public static String toBinary(int num) {
  if (num>0)
    return toBinary(num / 2) + (num % 2);
  else 
    return "";
}

Note that both this and the original are not very good binary converters because they don't handle 0 properly. Nor do they handle negative numbers.

We can fix for 0, and gracefully handle negative numbers like so:

public static String toBinary(int num) {
  if (num < 0)
    throw new IllegalArgumentException("Negative numbers not supported");
  else if (num == 0)
    return "0";
  else return toBinaryInternal(num);
}

private static String toBinaryInternal(int num) {
  if (num>0)
    return toBinaryInternal(num / 2) + (num % 2);
  else
    return "";
}

3 Comments

Slightly different way of doing it, and doesn't explain what was wrong with original code. Write a sentence or two. --- If you want to change (fix) the code, you should also make it work for a 0 value and for negative numbers while you are at it.
What is numm? If you meant num, then why write it, given that the only possible value is 0 at that point, so a plain else would suffice. Problem is that the code will now 0-prefix every number, e.g. input 42 will come out as "0101010". Also, the negative number error should be an exception, and why not support negative numbers too, e.g. -42 is "‭11111111111111111111111111010110‬"?
I was trying to keep it simple and stick close to OP's original code. If they wanted a method for production code, they wouldn't be taking this approach. I've updated the example to thow an exception and fixed the leading 0 issue.

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.