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

image.png
image.png

将使用与运算检查每一位

  1. public class Solution {
  2. public int hammingWeight(int n) {
  3. int count = 0;
  4. for (int i = 0; i < 32; i++) {
  5. if ((n >> i & 1) != 0) count ++;
  6. }
  7. return count;
  8. }
  9. }

巧妙地用 nn - 1 对比

剑指 Offer 15. 二进制中1的个数 - 图3

图片来源 https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/solution/mian-shi-ti-15-er-jin-zhi-zhong-1de-ge-shu-wei-yun