首页 > 其他 > 详细

LeetCode191:Number of 1 Bits

时间:2015-06-05 10:11:15      阅读:362      评论:0      收藏:0      [点我收藏+]
Write a function that takes an unsigned integer and returns the number of1‘ bits it has (also known as the Hamming weight).

For example, the 32-bit integer11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Hide Tags Bit Manipulation

判断一个无符号整数中1的个数,这个问题很简单。将其与1做按位运算,并不断将整数右移,直到移位后的数字为0,就是下面的解法一。

如果上面不是判断一个无符号整数中1的个数而是有符号整数中1的个数,由于有符号整数右移时左边是根据符号位来补全的,这样对于负数而言会出现无穷的循环,所以不可以像上面那样对整数进行移位,但是可以对1进行移位,因为左移不存在按符号位补全的问题。循环的次数是sizeof(int)*8。即下面的解法二。

两种解法的runtime:4ms

class Solution {
public:

/**
 * //解法一:移动数字本身,这种情况只对数字是无符号整型时才正确
    int hammingWeight(uint32_t n) {
        int base=1;
        int result=0;
        while(n)
        {
            if(n&base)
                result++;
            n>>=1;
        }
        return result;
    }
    */

    //解法二:移动基础的数字1,这种情况对于有符号和无符号数都成立
    int hammingWeight(uint32_t n) {
        int base=1;
        int result=0;
        for(int i=0;i<sizeof(uint32_t)*8;i++)
        {
            if(base&n)
                result++;
            base<<=1;
        }
        return result;
    }

};

LeetCode191:Number of 1 Bits

原文:http://blog.csdn.net/u012501459/article/details/46372251

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