190. Reverse Bits - Easy
前往題目
想法
- 沒想法,對
bit manipulation
不熟
思路
- 重複以下步驟
32
次,因為有32
個bit
- 把
result
左移1
,以空出最後一個bit
,然後把n的最後一個bit
加入(這樣n
的最後一位就會變成result
的第一位) - 把
n
往右移(去除最後一位)
Code
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0; // The result
for (int i = 0; i < 32; ++i) {
// Shift the res left by 1
// Add the last bit of n to it,
// so it becomes the first bit in res
res = (res << 1) | (n & 1);
n = n >> 1; // Right shift
}
return res;
}
}
190. Reverse Bits - Easy
https://f88083.github.io/2024/01/19/190-Reverse-Bits-Easy/