题目:
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?
解答:
如果这个函数被调用上千次上万次?效率就是最重要的,看到 bit 有关注重效率,必然是位运算为先。这道题最终答案,可以视为拆成一位一位值的和。
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans = 0;
int flag = 0;
while(n >= 1) {
if(n % 2) ans += 1<<(32 - flag - 1);
flag ++;
n = n/2;
}
return ans;
}
};