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?
Integer.toBinaryString(int)?0value and for any negative number.