- Given a positive integer A, the task is to count the total number of set bits in the binary representation of all the numbers from 1 to A.
A = 3
DECIMAL BINARY SET BIT COUNT
1 01 1
2 10 1
3 11 2
1 + 1 + 2 = 4
- I got correct output
Code is below
def solve(A):
ad = ''
for i in range(A + 1):
ad += str(bin(i).replace('ob',''))
return ad.count('1')
With Bit-wise
def solve(A):
count = 0
for i in range(A + 1):
while i > 0:
i= i & (i-1)
count += 1
return (count)
- In both scenarios I am getting
Time Limit Exceeded.