Reverse bits of a given 32 bits unsigned integer.
For example, given input 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?
Related problem: Reverse Integer
class Solution { public: uint32_t reverseBits(uint32_t n) { string s; while (n > 0){ s += to_string(n%2); n /= 2; } uint32_t m = 0; for (int i = s.size() - 1; i > -1; --i) if (s[i] == 49) m += pow(2, s.size() - 1 - i); m *= pow(2, 32 - s.size()); return m; } }; class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): #s = ''.join(list(bin(n)[2:][::-1]) + ['0']*(32 - (len(bin(n)) - 2))) 或者 s = bin(n)[2:][::-1] + '0'*(32 - (len(bin(n)) - 2)) return int(s, 2)