常用的位运算技巧如下

[LeetCode-191] Number of 1 Bits(判断一个整数中有多少个1)

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
 public int hammingWeight(int n){
        int numberOfOne = 0;
        while (n !=0){
            numberOfOne++;
            n = n&(n-1);

        }
        return numberOfOne;
    }

leetcode 231: Power of Two

Given an integer, write a function to determine if it is a power of two.

可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断   N & (N-1) 是否为0.

public class Solution {
    public boolean isPowerOfTwo(int n) {
       return n > 0 && ((n & (n - 1)) == 0 );
    }
}

Leetcode——338. Bit位计数

分析:
首先是一个数减1,对应二进制的变化就是最右的一个1变为0,而这个1右边的所有0变为1,即相当于包括最后一个1在内的右边所有位取反,例如12(1100)减1,得到11(1011),然后再与变化前的数12(1100)进行与&运算,得到8(1000),可以看出经过这样一个运算之后这个数的1的个数减少了一个,所以可以利用这个原理,得到res[i]=res[i&(i-1)]+1
 

public int[] countBits(int num){
        int[] res = new int[num+1];
        for (int i = 1; i <= num ; i++) {
            res[i] = res[i&(i-1)]+1;
        }
        return res;
    }