题解 | #查找输入整数二进制中1的个数#
查找输入整数二进制中1的个数
http://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dec;//保存输入的十进制数值
Stack<Integer> stack = new Stack<>();
int a;//保存余数
try{
while(true){
if(scanner.hasNextInt()){
dec = scanner.nextInt();
while(dec != 0){
a = dec % 2;//取余数
dec = dec / 2;//把被除数变成模运算后的商,继续下一轮取余运算
stack.push(a);//余数入栈
}
int count = 0;//用来计算1的个数
while(!stack.isEmpty()){
Integer b = stack.pop();
if(b.equals(1)){
count++;
}
}
System.out.println(count);//输出1的个数
}else break;
}
}catch (InputMismatchException e){
System.out.println("请输入1个十进制整数!");
}
scanner.close();
}
}