LeetCode || Number of 1 Bits

来源:互联网 发布:linux查找进程的命令 编辑:程序博客网 时间:2024/06/07 09:43

解法1: Accepted

耗时4ms。

但是没有考虑负数的情况,本题也没有测试这种情况。


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


解法2: Accepted

耗时4ms。

考虑了出现负数的情况,解决了陷入死循环的问题。

int hammingWeight(uint32_t n) {uint32_t tmp = 1;int count= 0;while(tmp)//会执行到tmp溢出结束{if(n & tmp)count++;tmp = tmp << 1;}return count;}

解法3: Accepted

耗时4ms。

减低了while的循环次数。

class Solution {public:    int hammingWeight(uint32_t n) {        int count= 0;        while(n)        {            count++;            n = n &(n-1);//相当于每次消灭一个1        }        return count;    }};



0 0
原创粉丝点击