Java – Convert Decimal to Binary using Recursion Java

binarydecimaljavarecursion

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

Best Solution

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

}