Skip to content

Commit 8c31bc9

Browse files
committed
Updated reverse bits
1 parent 35f9e27 commit 8c31bc9

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

Easy/ReverseBits.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,15 @@
1919
* Tags: Bit Manipulation
2020
*/
2121
class ReverseBits {
22+
2223
public static void main(String[] args) {
2324
ReverseBits r = new ReverseBits();
24-
// int a = 43261596;
25-
// System.out.println(r.reverseBits(a));
26-
// System.out.println(r.reverseBitsOpt(a));
25+
int a = 43261596;
26+
System.out.println(r.reverseBits(a));
27+
System.out.println(r.reverseBitsOpt(a));
2728

2829
int b = 1;
29-
// System.out.println(r.reverseBits(b));
30+
System.out.println(r.reverseBits(b));
3031
System.out.println(r.reverseBitsOpt(b));
3132
}
3233

@@ -40,10 +41,8 @@ public static void main(String[] args) {
4041
*/
4142
public int reverseBits(int n) {
4243
int res = 0;
43-
for (int i = 0; i < 32; i++) {
44-
res = (res << 1) ^ (n & 1); // add first bit of n to last bit of res
45-
n >>>= 1; // unsigned shift to right
46-
}
44+
// concat n's ith digit with res
45+
for (int i = 0; i < 32; i++) res = (res << 1) ^ ((n >>> i) & 1);
4746
return res;
4847
}
4948

0 commit comments

Comments
 (0)