輸入一個整數,輸出該數二進制表示中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); } } } }