Skip to content

Commit 8681b04

Browse files
committed
Reverse Bits
1 parent b6138ed commit 8681b04

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

reverse-bits/forest000014.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
runtime 0 ms, beats 100.00%
3+
memory 41.47 MB, beats 90.14%
4+
5+
time complexity: O(1)
6+
space complexity: O(1)
7+
8+
i번째 bit를 구하고, 이를 ans(초기값 0)의 31-i번째 자리에 bitwise-OR 연산을 하여, bit 위치를 reverse 했습니다.
9+
*/
10+
11+
public class Solution {
12+
// you need treat n as an unsigned value
13+
public int reverseBits(int n) {
14+
int x = 1;
15+
int ans = 0;
16+
for (int i = 0; i < 32; i++) {
17+
int bit = (x & n) >>> i;
18+
bit <<= (31 - i);
19+
ans |= bit;
20+
x <<= 1;
21+
}
22+
return ans;
23+
}
24+
}

0 commit comments

Comments
 (0)