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

吞佛童子2022年10月10日
  • algorithm
  • 位运算
小于 1 分钟

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

难度: 🌕🌗

问题描述

img_1.png


解法

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        // 思路:
        // 一个公式 n & (n - 1) 可以快速得到 1 的个数
        int res = 0;
        while(n != 0) {
            res ++;
            n = n & (n - 1);
        }
        return res;
    }
}

输出

img.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou