输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
输入: 输入可能包含多个测试样例。
对于每个输入文件,第一行输入一个整数T,代表测试样例的数量。对于每个测试样例输入为一个整数。
。n保证是int范围内的一个整数。
对应每个测试案例,
输出一个整数,代表输入的那个数中1的个数。
知识点:
- 正数的补码为它本身
- 负数的补码求法
- 补码 = 反码+1(比如:-1 补码:1111 1111 = 1111 1110 + 1);
- 补码 = 模-负数的绝对值(比如:-1 补码:1111 1111(10000 0000 -1得来));
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);
}
}
}
}