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!

1
  • Not related, but wouldn't it print the wrong value for 1? Commented May 30, 2017 at 23:09

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Kevin, it turns out the ' /= ' was the problem and all it needed was to be changed to ' / '
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.