LeetCode-Number of 1 Bits

问题描述

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

解题思路

这道题考察的就是求解一个整数的二进制表示法中有几个1,那么自然先想到第一种,即一位一位向右位移,数出1的个数,伪代码如下:

while(0 != n)
{
    left = n & 0x1;
    re += left;
    n = n >> 1;
}

但是此种方法较慢,对于0x1ffffff的判定需要循环32次才能计算出结果,超时。
故转换思路,举例:
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
看到这里已经得到了一种新的解法,n中本来有3个1,按照此种思路只需要循环3此即可求出最终结果,比第一种暴力枚举的解法要少很多次。最终实现代码如下,AC:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int re = 0;

        while(0 != n)
        {
            n = n&(n - 1);
            ++re;
        }

        return re;
    }
}
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值