Skip to main content

191. Number of 1 Bits

https://leetcode.com/problems/number-of-1-bits/

Python

Convert the type and count

class Solution:
def hammingWeight(self, n: int) -> int:
bins = str(bin(n))[2:]
return sum([int(char) for char in bins])

Hamming Weight

class Solution:
def hammingWeight(self, n: int) -> int:
total = 0
while n:
total += 1
n &= (n-1)
return total

Javascript

var hammingWeight = function(n) {
let count = 0;
while (n > 0) {
count += (n & 1);
n >>>= 1;
}
return count;
};