1. 程式人生 > 其它 >Java 位運算簡單使用

Java 位運算簡單使用

求n的二進位制第k位是

公式:n >> k & 1 ,k從0開始代表第幾位


public class Main {

    public static void main(String[] args) {
    	// 求10的二進位制數
        for (int i = 3; i >= 0; i--) {
            System.out.print(10 >> i & 1);
        }
    }
}

n & -n 可以求出n的二進位制中最後一位1

例如10:
10的二進位制是1010
-10的二進位制是先反碼再加一,就是0101 + 1 = 0110


1010 & 0110 = 10 十進位制也就是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

【思路:】
每次求出n的最末尾的1,然後拿n減去最右端的1,減一次就+1一次記錄數,等於0的時候結束

【程式碼:】

import java.io.*;

public class Main {
    
    public static void main(String[] args) throws IOException{
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(read.readLine());
        String[] str = read.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            int x = Integer.parseInt(str[i]);
            int res = 0;
            while(x > 0) {
                x -= f(x);
                res ++;
            }
            System.out.print(res + " ");
        }
        
    }
    
    private static int f(int x) {
        return x & -x;
    }
}