class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
rs = 0
while(n > 0):
if(n%2 == 1):
rs = rs + 1
elif ( n%2 == 0 ) and ( n/2 == 0 ):
rs = rs + 1
n = n/2
return rs
Easy Mistake to make:
In the first practice, I didn't add that, so for example, when n is 2, it would never let rs add one. because the result of mode would be Zero. So in order to deal with the missing of one for the last digit 1, I add:
elif ( n%2 == 0 ) and ( n/2 == 0 ):
It means after n = n/2, when n is 2, rs need add one anyway.
No comments:
Post a Comment