[leetcode_190]Reverse Bits

Convert a positive integer to binary, reverse the bit order, then output it as a decimal. A simulation problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        //To binary
        vector<int> nums(32, 0);
        int index = 0;
        while(n > 0)
        {
            nums[index++] = n % 2;
            n /= 2;
        }

        uint32_t ans = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            ans += nums[i] * (uint32_t)pow(2.0, (int)(nums.size() - i - 1));
        }
        return ans;
    }
};