It's fast because using bit-manipulation. Algorithm is O(logn), because each input n has number of logn binary digits.
In the while loop:
n shift 1 position right until become zero
if 2^0 == 1: count +1
class Solution(object): def hammingWeight(self, n): if n < 0: return bin(n).count('1') # correction according to Jun_Tang count = 0 while n > 0: count, n = count+(n&1), n>>1 return count
@Jun_Tang Thanks for your correction! Codes are updated, but sadly, the performance dropped from 39ms to 45ms. Wondering that why there's no negative numbers in test cases.