简体   繁体   中英

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. I ran two test cases:

For the number 28, the expected output should be 00111 but the output is 0111 : 在此处输入图像描述

For the number 5, the output should be 101 but the output is 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 . 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.

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