记录题解。
首先明白 负数在二进制运算中是以补码的形式进行的(正数其实就是他本身),那么让其不断进行无符号的右移 并和1进行与运算,便能统计出 二进制中 1 的个数了。
public class Solution {
public int NumberOf1(int n){
int count = 0;//用于统计二进制中1的个数
while ( n != 0){
if ((n&1) != 0){
count++;
}
n >>>= 1; // 无符号右移,和 1 进行 与运算 统计 二进制中1的个数
}
return count;
}
}官方提供的技巧法。
好处:省去了if判断的过程。
public class Solution {
public int NumberOf1(int n){
int ans = 0;
while (n != 0) {
++ans;
n = n & (n-1);
}
return ans;
}
}
京公网安备 11010502036488号