0

So I know how I would go about writing a function that would simply print out the converter integer into binary like this:

private void convertBinary(int num) {

    if(num > 0){

        convertToBinary(num/2);

        System.out.print(num%2 + "");

    }
}

However, I'm not sure how I would do this if I wanted to return it as a string, especially with recursion since if I initialize the string as the beginning of the method it will reset the string during each recursive call.

Test
  • 99
  • 1
  • 2
  • 8
  • 3
    You start by changing the method to return `String`, then capture return value on recursive call. Now that you have value from recursive call, you can append to it, instead of printing. See where that leads you, one step at a time. – Andreas Feb 21 '17 at 17:29
  • Possible duplicate of [Converting Decimal to Binary Java](http://stackoverflow.com/questions/14784630/converting-decimal-to-binary-java) – Prune Feb 21 '17 at 17:33
  • It's not a dupe (at least, not of that) -- it's a "help me learn recursion" question. – slim Feb 21 '17 at 17:38

3 Answers3

0

Advice 1: function name ... ConvertToBinary vs ConvertBinary
Advice 2: your result will be reverted this way (lsb on left)
Advice 3: get the return value from conversion and concatenate it with n%2 as output

But you're close enough.

BTW is it for some educational purpose? Recursion is quite inefficient for converting something to binary :)

B.Adler
  • 1,499
  • 1
  • 18
  • 26
dkellner
  • 8,726
  • 2
  • 49
  • 47
0

Rather than give you code you can copy/paste, I'll solve a similar problem and you can apply the same technique.

Here's the print version of recursively printing 'A' n times:

  void printTimes(int n) {
      if(n > 0) {
          printTimes(n-1);
          System.out.print("A");
      }
  }

Now here's a version that returns a String:

  String stringTimes(int n) {
       if(n > 0) {
           return stringTimes(n-1) + "A";
       } else {
           return "";
       }
  }

This should help you write your toBinary method.


Although this is close to your original, I like to be consistent in my recursive methods, in handling the terminating clause first, so more like:

  String stringTimes(int n) {
      if(n == 0) {
          return "";
      }

      return stringTimes(n - 1) + "A";
  }

Note that recursion is only appropriate to this particular problem, in Java, for learning purposes.

slim
  • 40,215
  • 13
  • 94
  • 127
0
class Class {

  public static void main(String... args) {
    System.out.println(intToBinary(1));
    System.out.println(intToBinary(8));
    System.out.println(intToBinary(15));
    System.out.println(intToBinary(1234567));
  }

  private static String intToBinary(final int i) {
    if (i == 0) {
      return "";
    } else {
      return intToBinary(i / 2) + Integer.toString(i % 2);
    }
  }
}
Andreas
  • 4,937
  • 2
  • 25
  • 35