Skip to content

Commit 9fea5c6

Browse files
committed
week8: reverse-bits
1 parent 45010ac commit 9fea5c6

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

reverse-bits/reeseo3o.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time Complexity: O(1)
2+
// Space Complexity: O(1)
3+
4+
const reverseBits = (n) => {
5+
let result = 0;
6+
7+
// 32비트 고정 - 정확히 32번
8+
for (let i = 0; i < 32; i++) {
9+
// 1. n의 마지막 비트만 뽑기 (0 또는 1)
10+
const bit = n & 1;
11+
12+
// 2. result를 한 칸 왼쪽으로 밀고, 거기에 bit를 붙이기
13+
result = (result << 1) | bit;
14+
15+
// 3. n은 오른쪽으로 한 칸 밀어서 다음 비트 준비
16+
n >>>= 1;
17+
}
18+
19+
// 항상 32비트 unsigned로 보이게 하기 위해 마지막에 한 번 더 >>> 0
20+
return result >>> 0;
21+
};
22+

0 commit comments

Comments
 (0)