Skip to content

Commit 579021b

Browse files
committed
feat: solve reverse bits
1 parent 50dcab4 commit 579021b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

reverse-bits/GangBean.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
// you need treat n as an unsigned value
3+
public int reverseBits(int n) {
4+
/**
5+
1. understanding
6+
- return the reversed 32 bit input num
7+
2. strategy
8+
- assign stack
9+
- iterate until stack.size is 32
10+
- push value % 2, and value /= 2
11+
3. complexity
12+
- time: O(1)
13+
- space: O(1)
14+
*/
15+
int reversed = 0;
16+
for (int i = 0; i < 32; i++) {
17+
reversed <<= 1;
18+
reversed |= n & 1;
19+
n >>= 1;
20+
}
21+
return reversed;
22+
}
23+
}
24+

0 commit comments

Comments
 (0)