dev

Alg - 4.3 Bit Manipulation

/note-bak/dev/alg/bit-manipulation/

4.3 Bit Manipulation

Bitwise Operator

NOT ( ~ )
AND ( & )
OR ( | )
XOR ( ^ )
Left Shift ( << )
Right Shift ( >> )

Shift

>>> compare to >>

>>> is logical shift, also known as unsigned shift, it moves every bit

01111111 >>> 2 = 00011111
10000000 >>> 2 = 00100000

>> is arthematic shift, also known as signed shift, it does not move the sign bit

01111111 >> 2 = 00011111
10000000 >> 2 = 11100000

Get Bit

取得最低位的二进制数0/1:int bit = num & 1

对于一个32位数,依次取其低位的二进制数:

for(int j=0; j<32; j++) {
	int bit = num & 1;
	num >>= 1;
}

Example

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 class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
    		while(n != 0) {
    			count += n&1;
    			n >>>= 1;
    		}
    		return count;
    }
}