LeetCode-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?

题解:

注意32位即可

class Solution {
public:
  string getBin (uint32_t n) {
    string res;
    while (n > 0) {
      res += to_string(n % 2);
      n /= 2;
    }
    while (res.size() != 32) {
      res += '0';
    }
    return res;
  }
  uint32_t toDec (string s) {
    reverse(s.begin(), s.end());
    uint32_t a = 0;
    uint32_t res = 0;
    for (int i = 0; i < s.length(); i++) {
      res += pow(2, a) * (s[i] - 48);
      a++;
    }
    return res;
  }
  uint32_t reverseBits(uint32_t n) {
    return toDec(getBin(n));
  }
};

猜你喜欢

转载自blog.csdn.net/reigns_/article/details/84720981
今日推荐