题解 | #求int型正整数在内存中存储时1的个数#
求int型正整数在内存中存储时1的个数
http://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9
易理解JAVA写法
将二进制数字每次右移>>1 计算余数有1 就有一个1,余数0就没1,不过这种写法的最坏情况就是要遍历完32次
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int a = in.nextInt();
int c= 0;
while( a!=0){
int t =a %2 ;
if(t==1){
c++;
}
a = a >>1;
}
System.out.println(c);
}
} 

查看3道真题和解析