简体   繁体   English

如何在使用朴素递归将十进制数字转换为二进制数字时捕获第一位数字?

[英]How to capture the first digit while converting a decimal number to binary digit using naive recursion?

I am trying to convert a decimal number to a binary digit in the below way using recursion.我正在尝试使用递归按以下方式将十进制数转换为二进制数。

def getbin(x: int, s: str):
    if int(x/2) > 0:
        y = int(x/2)
        s += str(y % 2)
        print(f'int(x/2): {int(x/2)}, y: {y}, st: {s}')
        getbin(y, s)
    elif int(x/2) == 1:
        s += '11'
        return s


if __name__ == '__main__':
    print(getbin(28, ''))

But when I call this, I can see in the output that the first digit of the binary number is not getting captured.但是当我调用它时,我可以在 output 中看到二进制数的第一位没有被捕获。 I ran two test cases:我运行了两个测试用例:

For the number 28, the expected output should be 00111 but the output is 0111 :对于数字 28,预期的 output 应该是00111但 output 是0111 在此处输入图像描述

For the number 5, the output should be 101 but the output is 01对于数字 5,output 应该是 101 但 output 是01 在此处输入图像描述

Could anyone let me know what is the mistake I am making here and how can I correct it?谁能让我知道我在这里犯的错误是什么,我该如何纠正?

Your problem is that you are testing against x/2 instead of testing against x .您的问题是您正在针对x/2而不是针对x进行测试。 Thus you lose the most significant bit of the result.因此,您丢失了结果中最重要的部分。 Try something like this:尝试这样的事情:

def getbin(x: int, s: str):
    s += str(x % 2)
    y = x // 2
    if y > 0:
        return getbin(y, s)
    return s

Note also that you need to reverse the result of getbin to get the correct binary string.另请注意,您需要反转getbin的结果才能获得正确的二进制字符串。

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

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