二进制中1的个数,两种解法
二进制中1的个数
http://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8
解法一
直接利用Integer提供的API将数字转化为二进制表示的字符串,然后就可以直接通过charAt()记录1的个数,或者使用replace()把0给替换掉再返回字符串长度。
public class Solution {
// replace替换
public int NumberOf1(int n) {
return Integer.toBinaryString(n).replace("0","").length();
}
// 遍历字符串记录
public int NumberOf1(int n) {
String str = Integer.toBinaryString(n);
int length = str.length();
int count = 0;
for (int i=0; i<length; i++) {
if (str.charAt(i) == '1') {
count++;
}
}
return count;
}
} 解法二
将数字与1进行与运算,返回结果为1则表明数字二进制最后一位是1,通过对不断数字右移运算判断有多少个1。
public class Solution {
public int NumberOf1(int n) {
int res = 0;
while (n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
} 

