简体   繁体   English

使用递归将十进制转换为二进制

[英]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. 它应该将十进制转换为二进制,但是只显示“ 0”而不是二进制字符串。 Could someone tell me what I'm doing wrong please? 有人可以告诉我我在做什么错吗?

You should return the bin variable: 您应该返回bin变量:

else
    return bin;

You also want to prepend Integer.toString(number % 2) to the previous String, not append it: 你也想在前面加上 Integer.toString(number % 2)以前的字符串,而不是追加它:

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. 我认为您可能是指return bin ,因为您正在累积到该字符串中。 You're just discarding bin in your current implementation. 您只是在当前的实现中丢弃bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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