剑指 Offer 15 二进制中1的个数

标签: 剑指 Offer 发布于:2022-02-23 09:37:41 编辑于:2022-02-23 09:57:26 浏览量:943

概述

https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/

https://leetcode.com/problems/number-of-1-bits/

利用 n & 1 判断是否最后一位为 1

注意,对于负数,右移会有问题,因为其会补 1,更方便的解法是左移 1:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        uint a = 1;
        for (int i = 0; i < 32; i ++) {
            if (n & a) count ++;
            a = a << 1;
        }
        return count;
    }
};

注意哦,a 是无符号整型,你移动 int 的话,要避免最后一次不必要的左移:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        int a = 1;
        for (int i = 0; i < 32; i ++) {
            if (n & a) count ++;
            if (i == 31) break;
            a = a << 1;
        }
        return count;
    }
};

利用 n & (n - 1) 消去最右边的 1

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

未经允许,禁止转载,本文源站链接:https://iamazing.cn/