Skip to content

Commit 1311eee

Browse files
solves reverse bits
1 parent 2817ace commit 1311eee

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/ReverseBits.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class ReverseBits {
2+
public int reverseBits(int n) {
3+
for (int i = 0; i < 16; i++) {
4+
n = swapBits(n, i, 32 - i - 1);
5+
}
6+
7+
return n;
8+
}
9+
10+
public int swapBits(int n, int i, int j) {
11+
int a = (n >> i) & 1;
12+
int b = (n >> j) & 1;
13+
14+
if ((a ^ b) != 0) {
15+
return n ^= (1 << i) | (1 << j);
16+
}
17+
18+
return n;
19+
}
20+
}

0 commit comments

Comments
 (0)