public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
//0(二进制表示为0000)和一个数与运算,相当于这个数的二进制按位取0
//1(二级制表示为0001)和一个数与运算,相当于这个数的二进制最后一位保留,高位都置为0
int res = 0;
//依次判断n的二进制每一位是否为1,时间复杂度为O(32),对于32位整数而言
// for (int i = 0; i < 32; i ++) {
// if (n & (1 << i) != 0) {
// res ++;
// }
// }
//使用n & (n - 1)会将n的最后一位1置为0这一个特性判断
//时间复杂度为O(logN),logN为N的二进制表示中1个总个数
while (n != 0) {
n &= (n - 1);
res ++;
}
return res;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
for(int i = 0;i<32;i++){
if((n&(1<<i))!=0){
res++;
}
}
return res;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
return Integer.toBinaryString(n).replace("0", "").length();
}
}
2、通过n&(n-1),移除最右边的1
public class Solution {
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n-1);
count++;
}
return count;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
// n & (n-1) 可以消除n最右边的一个1(二进制表示)
n = n & (n - 1);
count++;
}
return count;
}
}
共以下 9 个回答
位运算熟能生巧,且需注意if中与或非计算的优先级低于等于的优先级
自己写的好像没用提示给出的公式。看看答案
按位检查
1、利用Integer.toBinaryString()
2、通过n&(n-1),移除最右边的1
利用n&(n-1)消除最右边的1
时间复杂度:O(logN), 空间复杂度:O(1)