https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tqId=11164&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
| 日期 | 是否一次通过 | comment |
|----|----|----|
|2019-01-26 13:20|N|n & (n-1)能将二进制数中最低位1置零|
|2019-01-27 13:20|N||
题目:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
补码解释:
http://www.ruanyifeng.com/blog/2009/08/twos_complement.html
1. 递归
public class Solution {
public int NumberOf1(int n) {
int count = 0;
if(n == 0) {
return count;
}
count += NumberOf1(n & (n-1));
return count + 1;
}
}
2.非递归
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while(n != 0) {
count ++;
n = n&(n-1);
}
return count;
}
}