Python Forum
Incrementing binary number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Incrementing binary number
#1


Hello, I got this assignment of incrementing a binary number (which displays as a string) without using base converting.

i wrote the code which i think is pretty good, but i got stuck with an error message when used this line of code:
return ''.join(lst_binary.insert(0,'1'))
that happens when the prog gets a string like '111', and needs to add another digit at the end of number.

the error i got was
Error:
"TypeError: can only join an iterable"
while was debugging with python-tutor

this is the whole code:
def inc(binary):
    lst_binary = list(binary)
    for bit in range(len(binary)-1, -1, -1):
        if lst_binary[bit] == '0':
            lst_binary[bit] = '1'
            return ''.join(lst_binary)
        else:
            lst_binary[bit] = '0'
    return ''.join(lst_binary.insert(0,'1'))
im not looking though for other ways to do this, just to understand why this line doesnt work
Reply


Messages In This Thread
Incrementing binary number - by Danielk121 - Nov-10-2017, 10:34 AM
RE: Incrementing binary number - by DeaD_EyE - Nov-10-2017, 11:40 AM
RE: Incrementing binary number - by Danielk121 - Nov-10-2017, 12:04 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020