输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
解法一:直接右移遍历,简单明了
public class Solution {
public int NumberOf1(int n) {
int count=0;
while(n!=0){
count +=(n&1);// 判断最低位是否为1/0
n>>>=1; // 无符号右移一位
}
return count;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
解法二:使用左移,逐位比对
public class Solution {
public int NumberOf1(int n) {
int count=0;
int s =1;
while(s>0){
if((s&n)>0){
++count ;
}
s<<=1;
}
return n<0?count+1:count; // 负数的时候+1,因为符号位用补码替换了
}
}
时间复杂度:O(n)
空间复杂度:O(1)
练习地址:https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8