简体   繁体   中英

Trying to recursively convert an integer to binary in String format in Java?

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?

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 eg

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

Output:

10111

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM