題目網址:https://leetcode.cn/problems/reverse-bits/

題意:給一無號整數 n, 請將其二進制進行反轉。

Solution:

想法:每次先把 res 的最右 bit 設為 0(左移一位, 最右 bit 補 0), 然後取得 n 的最右 bit(對 n 的最右 bit 取 OR), 做完後將 n 右移一位(捨棄最右 bit)

class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;

for (int i = 0; i < 32; ++i) {
res <<= 1; // 最右 bit 設 0
res |= (n & 1); // 得到 n 的最右 bit
n >>= 1; // 捨棄最右 bit
}

return res;
}
};
  • time:$O(1)$ ➔ for loop 只需 $O(32)$
  • space:$O(1)$ ➔ 只需常數空間