Java Recursive Decimal to Binary Function Printing Backwards

Viewed 2010

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!

2 Answers
Related