Leetcode NO.191 Number of 1 Bits

来源:互联网 发布:有线键鼠套装推荐 知乎 编辑:程序博客网 时间:2024/05/27 14:13

本题题目要求如下:

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

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

本题难度并不高。。。就是数1的位数,我的算法是每次就跟1按位与。。如果等于1则count加一,然后n每次都右移一位。。最多移动32位。

代码如下:

class Solution {public:    int hammingWeight(uint32_t n) {    int count = 0;        while (n) {        if (n & 1)        ++count;        n >>= 1;        }        return count;    }};

讨论区里面有更好的算法,时间复杂度是O(m),m为1的个数。。。


0 0
原创粉丝点击