leetcode-190-reverse bits

Problem Description:

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

题目大意:

反转一个32位整数(原来是0,1,2,3,…32, 变成 32,31,30…,1)

Solutions:

简单的位运算操作。

Code in C++:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t res = 0 ;
        int mask = 1 ;
        for(int i = 0 ; i <  32 ; i ++)
        {
            if( n & mask ) res += 1 ;
            if(i < 31)res <<=  1 ;
            mask <<= 1;
        }
        return res;
    }
};