以前在力扣上做过只有正数的1的个数,是可以用动态规划来做的。
这里的题按照书本所说,需要考虑到负数的情况。
负数就非常麻烦。
比如-10。
正数是:0000…1010
但是负数是:11111…0101(30个1,2个0)
在书上有两种方法:
一种是技巧法,可以记住,但是不适合现场想出来。
即:
n 与 n-1 相与会把最右边的一个1给去掉。
public class Solution {
public int NumberOf1(int n) {
//技巧法
int count = 0;
while(n != 0){
int temp = n - 1;
n = (n & temp);
count++;
}
return count;
}
}
老实一点的方法
请注意在java里面是不能用int来进行判断的。
public class Solution {
public int NumberOf1(int n) {
//老实法
int i = 1;
int count = 0;
while(i != 0){
if((i&n) != 0){
count++;
}
i = i << 1;
}
return count;
}
}