首页 > 其他 > 详细

Leetcode16: Number of 1 Bits

时间:2015-04-23 10:56:40      阅读:177      评论:0      收藏:0      [点我收藏+]

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.

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int k = 0;
        while(n)
        {
            k += (n & 0x1) > 0 ? 1 : 0; //(n % 2) > 0 ? 1 : 0;
            n >>= 1;                    //n /= 2;
        }
        return k;
    }
};

技术分享

这是比较容易想到的解决办法,每次判断最后一位是否是1。但是这样32位的数最坏的情况要比较32次。有没有更简单的方法呢?


下面这种方法更为简单。假设n= 1111000111000 那 n-1 = 1111000110111, (n-1) & n = 1111000110000,刚好把最后一个1给干掉了。也就是说, (n-1)&n 刚好会从最后一位开始,每次会干掉一个1.这样速度就比上面哪种方法快了。有几个1,就执行几次。(学渣表示震惊!= =)

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int k = 0;
        while(n != 0)
        {
            n = n & (n-1);
            k++;
        }
        return k;
    }
};

技术分享

Leetcode16: Number of 1 Bits

原文:http://blog.csdn.net/u013089961/article/details/45217825

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!