Photo by Dominik Scythe on Unsplash
Write an algorithm that finds the total number of set bits in all integers betweenhttps://dailycodingproblem.com
Today I decided that I would switch up my coding problem language and give python a try. Unfortunately, the syntax highlighter that is used does not have python as an option, but feel free to view the code using the button below.
# Helper method to convert a number to binary def convertToBinary(num): return str(bin(num))[2:] # The main method def bits(n): if n == 0: return 0 else: binary = convertToBinary(n) count = binary.count('1') return count + bits(n - 1) # Should return 4 print(bits(3)) # Should return 2222 print(bits(500))