1. 程式人生 > >leetCode 190-Reverse Bits

leetCode 190-Reverse Bits

此題的關鍵是預先將1<<i的數字存入一個大小為32的陣列中,然後通過x & (1 << i)來獲得x的第i位是不為0的判斷.進行求和即可。

class Solution {
public:
    Solution(){
        unsigned int i = 0;
		unsigned int j = 1;
		for(; i < 32; i++)
			a[i] = (j<<(31-i));
	}
	unsigned int reverseBits(unsigned int n) {
        unsigned int reverseBit = 0;
        for(unsigned int i = 0; i < 32; i++){
            if((n & (1 << i)) != 0) reverseBit += a[i];
        }
        return reverseBit;
    }
private:
    unsigned int a[32]; 
};