简体   繁体   中英

Convert decimal to binary using recursion

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM