题目1513:二进制中1的个数
重点是右移ptr而不是把n左移,为了避免左移负数的问题
和
用不等于0来判断避免了繁琐!
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class S10 {
public static void main(String[] args) throws FileNotFoundException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("S10.in"));
System.setIn(in);
Scanner cin = new Scanner(System.in);
while (cin.hasNextInt()) {
long n = cin.nextInt();
for(int i=0; i<n; i++){
System.out.println(get1s(cin.nextInt()));
}
}
}
public static int get1s(int n){
int cnt = 0;
int ptr = 1;
for(int i=0; i<32; i++){ // 重点是右移ptr而不是把n左移,为了避免左移负数的问题
if((n&(ptr<<i)) != 0){ // 用不等于0来判断避免了繁琐!
cnt += 1;
}
}
return cnt;
}
}