🌕🌗 剑指 Offer 15. 二进制中1的个数
2022年10月10日
- algorithm
🌕🌗 剑指 Offer 15. 二进制中1的个数
难度: 🌕🌗
问题描述
解法
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;
}
}