主要考察的位运算,基础知识薄弱 需加强记忆
做这道题的前提,首先进行熟悉一下我们的位运算:位运算概念
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
//1. 直接进行按位 &的循环遍历比较
// int res = 0;
// if (n != 0){
// for (int i = 0; i < 32; i++) {
// if ((n & 1 << i) != 0){
// res++;
// }
// }
// }
// return res;
//2. 利用位特性进行取值 每次将最低为进行翻转
int count = 0;
while (n != 0){
n &= n-1;
count++;
}
return count;
}
}
总结:注重基础知识,打牢基础