4

I am coding a Lab exercise for one of my classes. The question asks to "Write a recursive function convert a decimal number into a binary number, printing the binary number" Using the constructor public static void decToBin(int num){}

Current code:

public class convert {
    public static void decToBin(int num) {
        if (num > 0) {
            decToBin(num /= 2);
            System.out.print(num % 2);
        }
    }

    public static void main(String[] args) {
        decToBin(50);
    }
}

Output: 011001

Unfortunately, when the program unpacks all the methods that were called and ends them it prints out my number in binary but backwards. I have tried just about everything under the sun and nothing works for me.

If anybody could tell me where the problem lies, give me a hint or anything. I just need a second opinion on this code. Thank you!

Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
BigChemist
  • 43
  • 4

2 Answers2

3

You're dividing by 2 before you print out your answer which is messing with the result. The corrected function would be.

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

Then to reverse the order, you can flip the lines.

public static void decToBin(int num) {
    if (num > 0) {
        System.out.print(num % 2);
        decToBin(num / 2);
    }
}
Kevin
  • 400
  • 5
  • 15
0

First of all, you need to print num % 2 before calling the function on num /= 2. and you need to reverse the output to get the binary number because when converting to binary you type the numbers from right to left.

Mohd
  • 5,523
  • 7
  • 19
  • 30