2021.09.28 - 094.位1的个数

1. 题目

在这里插入图片描述

2. 思路

(1) Integer.bitCount()

  • 调用方法即可。

(2) 位运算

  • n & (1 << i)会检查n的每一个二进制位上是否为1。

(3) 位运算优化

  • n & (n - 1)会将最低位的1变成0。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public int hammingWeight(int n) {
    
    
        return Integer.bitCount(n);
    }
}

class Solution1 {
    
    
    public int hammingWeight(int n) {
    
    
        int count = 0;
        for (int i = 0; i < 32; i++) {
    
    
            if ((n & (1 << i)) != 0) {
    
    
                count++;
            }
        }
        return count;
    }
}

class Solution2 {
    
    
    public int hammingWeight(int n) {
    
    
        int count = 0;
        while (n != 0) {
    
    
            n &= n - 1;
            count++;
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120522878