题解 | #查找输入整数二进制中1的个数#
查找输入整数二进制中1的个数
http://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
int input = sc.nextInt();
System.out.println(getSum(input));
}
}
public static int getSum(int i){
//判断最后一位是否为1,然后一直向右移位, 直到将输入的整数变成0结束
int sum=0;
for(int j=0;j<32;j++){
if(i%2==1){
sum++;
}
i = i>>> 1;
if(i==0){
break;
}
}
return sum;
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
int input = sc.nextInt();
System.out.println(getSum(input));
}
}
public static int getSum(int i){
//判断最后一位是否为1,然后一直向右移位, 直到将输入的整数变成0结束
int sum=0;
for(int j=0;j<32;j++){
if(i%2==1){
sum++;
}
i = i>>> 1;
if(i==0){
break;
}
}
return sum;
}
}