0

I got the following code:

public class decToBin {

public static void main(String args[]) {

    int number = 32;

    System.out.println(decToBinWrapper(number));
}

public static String decToBinWrapper(int number) {

    return decToBin(number, "");
}

public static String decToBin(int number, String bin) {
    if (number >= 1)
        return decToBin(number / 2, bin + Integer.toString(number % 2));
    else
        return "0";

}
}

which is supposed to convert a decimal to binary but it only prints "0" instead of the binary string. Could someone tell me what I'm doing wrong please?

2
  • 1
    Just in case it's useful to you: Integer.toBinaryString() Commented Feb 8, 2015 at 2:52
  • There is no decimal here. number is already binary. Commented Aug 22, 2017 at 4:31

2 Answers 2

3

You should return the bin variable:

else
    return bin;

You also want to prepend Integer.toString(number % 2) to the previous String, not append it:

return decToBin(number / 2, Integer.toString(number % 2) + bin);
Sign up to request clarification or add additional context in comments.

Comments

1
else
    return "0";

I think you probably meant return bin, since you're accumulating into that string. You're just discarding bin in your current implementation.

1 Comment

He also needs to prepend values, not append to make the digit order be correct

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.