Skip to content

Instantly share code, notes, and snippets.

@kaashmonee
Created October 16, 2017 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaashmonee/7708f3046543c63f4252c99867e0ecf4 to your computer and use it in GitHub Desktop.
Save kaashmonee/7708f3046543c63f4252c99867e0ecf4 to your computer and use it in GitHub Desktop.
Counts the number of times you have to carry when you add 1 to a binary number.
def countCarries(number):
number+=1
number = str(number)
number = list(number)
carries = 0
for x in range(len(number)-1, -1, -1):
if int(number[x])==2:
carries+=1
if number[x-1]:
number[x-1]=str(int(number[x-1])+1)
print(carries),
return carries
def run(runNum):
myList=[]
for i in range(0,runNum):
temp = countCarries(int(format(i,"b")))
myList.append(temp)
print "\n"+str(sum(myList))
numberToRun = input("how many numbers: ")
run(numberToRun)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment