190. Reverse Bits

问题描述:

Reverse bits of a given 32 bits unsigned integer.

Example:

Input: 43261596
Output: 964176192
Explanation: 43261596 represented in binary as 00000010100101000001111010011100, 
             return 964176192 represented in binary as 00111001011110000010100101000000.

Follow up:
If this function is called many times, how would you optimize it?

解题思路:

我想到的方法是检查数字的每一位,如果该位为一,则在ret中加上1<<(31-i)来达到反转位的作用

空间复杂度O(1)  时间复杂度:O(1) (因为我们每次都检查32位)

使用或操作能够避免重新构造新的数字,节省一定时间

follow up: 我认为可以用一个全局变量的map来存储对应。

代码:

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

更快的解法:

用到了比特操作符或操作来判断,省去了重新构造数字的过程

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
    uint32_t ans = 0;
    for (int i = 0; i < 32; i++, n >>= 1) {
        ans <<= 1;
        ans |= n & 1;
    }
    return ans;
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9485378.html