题解 | #查找输入整数二进制中1的个数#
查找输入整数二进制中1的个数
https://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad
package NewComer.Simple; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class HJ62_查找输入整数二进制中1的个数 { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int a = in.nextInt(); List<Integer> list = new ArrayList<>(); int c = -1; int b = 100; while(b/2!=0){ //十进制整数转换为二进制整数采用 "除 2 取余,逆序排列" 法。 c = a%2; b = a/2; a = b; list.add(c); } list.add(b%2); Collections.reverse(list); int count = 0; for(Integer aChar:list){ if(aChar == 1) ++count; } System.out.println(count); } } }