[NeetCode 150] Number of One Bits

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:

  1. The binary number is ends with 111. Let n=0bB1n=0bB1n=0bB1, then n−1=0bB0n-1=0bB0n1=0bB0 and n&(n−1)=0bB0n \& (n-1) = 0bB0n&(n1)=0bB0. The tail 1 disappears.
  2. The binary number is ends with 000. Let n=0bB10…0n=0bB10\ldots0n=0bB100, then n−1=0bB01…1n-1=0bB01\ldots1n1=0bB011 and n&(n−1)=0bB00…0n\&(n-1)=0bB00\ldots0n&(n1)=0bB000. 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 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值