输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 java
输入: 输入可能包含多个测试样例。
对于每一个输入文件,第一行输入一个整数T,表明测试样例的数量。对于每一个测试样例输入为一个整数。
。n保证是int范围内的一个整数。 测试
对应每一个测试案例,
输出一个整数,表明输入的那个数中1的个数。 code
知识点: io
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; /** * 二进制中1的个数 * @author aqia358 * */ public class Main { public static void count(int t) { if (t >> 31 == 0) { System.out.println(num(t)); }else{ long a = 1; int b = (int)(a << 32) + t; System.out.println(num(b)); } } public static int num(int t) { int count = 0; int n = 0; while (n < 32) { n++; if ((t & 1) != 0) { count++; } t >>= 1; } return count; } public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); while(st.nextToken() != st.TT_EOF){ int n = (int) st.nval; while(n > 0){ n -- ; st.nextToken(); count((int) st.nval); } } } }