The basic algorith , bit operation.
Basic has two module .
One , (n >> k & 1) is to cal the ith of a number is 0 or 1.
For example , n = 10 = (1010)2,
so n >> 0 & 1 = 0;
n >> 1 & 1 = 1;
n >> 2 & 1 = 0;
n >> 3 & 1 = 1;
Two , (n & -n) is to cal the last 1 the number with.
For example , n = (1000101000)2 (n & -n) = (1000)2
给定一个长度为n的数列,请你求出数列中每个数的二进制表示中1的个数。
输入格式
第一行包含整数n。
第二行包含n个整数,表示整个数列。
输出格式
共一行,包含n个整数,其中的第 i 个数表示数列中的第 i 个数的二进制表示中1的个数。
数据范围
1≤n≤100000,
0≤数列中元素的值≤109
输入样例:
5
1 2 3 4 5
输出样例:
1 1 2 1 2
Use the second module .
Code :
import java.io.*;
public class Main{
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter pw = new PrintWriter(System.out);
static int n, nums[];
public static void main(String args[]) throws Exception {
st.nextToken();
n = (int)st.nval;
nums = new int[n];
for (int i = 0 ; i < n ; i ++) {
st.nextToken();
nums[i] = (int)st.nval;
}
for (int i = 0; i < n ; i++ ){
int ans = 0;
while (nums[i] != 0) {
nums[i] -= lowbit(nums[i]);
ans++;
}
System.out.print(ans + " ");
}
}
private static int lowbit(int n){
return n & -n;
}
}