Number of One Bits
You are given an unsigned integer n. Return the number of 1 bits in its binary representation.
You may assume n is a non-negative integer which fits within 32-bits.
Example 1:
Input: n = 00000000000000000000000000010111
Output: 4
Example 2:
Input: n = 01111111111111111111111111111101
Output: 30
Solution
A straightforward solution to this problem is to divide the number by 2 and check the remainer of mod 2 until the number turns into 0.
However, there is a cooler solution that we use n & (n-1) to transform nnn until n=0n=0n=0. In each transform, the number of 1s in nnn will be reduced by 1. We can discuss this property in 2 cases:
- The binary number is ends with 111. Let n=0bB1n=0bB1n=0bB1, then n−1=0bB0n-1=0bB0n−1=0bB0 and n&(n−1)=0bB0n \& (n-1) = 0bB0n&(n−1)=0bB0. The tail 1 disappears.
- The binary number is ends with 000. Let n=0bB10…0n=0bB10\ldots0n=0bB10…0, then n−1=0bB01…1n-1=0bB01\ldots1n−1=0bB01…1 and n&(n−1)=0bB00…0n\&(n-1)=0bB00\ldots0n&(n−1)=0bB00…0. The tail 1 still disappears.
Therefore, we can repeat this process TTT times until nnn becomes 0 and TTT is the answer.
Code
Modulo
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
while n > 0:
ans += n%2
n //= 2
return ans
Bit operation
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
while n > 0:
n &= (n-1)
ans += 1
return ans

被折叠的 条评论
为什么被折叠?



