LeetCode_number-of-1-bits

来源:互联网 发布:矩阵的布尔积运算法则 编辑:程序博客网 时间:2024/04/29 16:22

原题链接:https://leetcode.com/problems/number-of-1-bits/

递归解法:class Solution {public:    int hammingWeight(uint32_t n) {        if(n == 0)            return 0;        if(n % 2 == 1)            return hammingWeight(n/2)+1;        else            return hammingWeight(n/2);    }};迭代解法:class Solution {public:    int hammingWeight(uint32_t n) {        int cnt = 0;        while(n)        {            if(n % 2 == 1)                cnt++;            n = n / 2;        }        return cnt;    }};


0 0