So.. yeah... that's the question. I've to count the number of 1 in a positive number. So for this, the approach was to do the bitwise and . We take the number and subtract 1 from it and and the two number until it becomes zero.
Here is the code:
def countOnes(num):
cnt = 0
while num:
num = num & (num-1)
cnt += 1
return cntSo, for num = 3, let's simulate the code:
1) cnt = 0
num = 3(11)
num - 1 = 2(10)
num = num & (num-1) =
11
& 10
------
= 10
cnt = 1
2) cnt = 1
num = 2(10)
num - 1 = 1(01)
num = num & (num-1) =
10
& 01
-----
= 00
cnt = 2
3) The loop breaks as now num = 0So this method works. But what is the significant here? What's the pattern? Why does this work? I mean I understand that you and two adjacent number and after some times it becomes 0 but why? Does it have any proof?
Any answer to the question is helpful.
Thanks