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

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));
  }
};