Skip to content

Commit acaee0f

Browse files
refactor 190
1 parent 92c5e45 commit acaee0f

File tree

1 file changed

+17
-30
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+17
-30
lines changed
Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,5 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 190. Reverse Bits
5-
* Reverse bits of a given 32 bits unsigned integer.
6-
7-
Example:
8-
Input: 43261596
9-
Output: 964176192
10-
11-
Explanation: 43261596 represented in binary as 00000010100101000001111010011100,
12-
return 964176192 represented in binary as 00111001011110000010100101000000.
13-
14-
Follow up:
15-
If this function is called many times, how would you optimize it?
16-
*/
17-
183
public class _190 {
194
/**delimiting the binary string into 4 bits array will make it easier to see/visualize:
205
* original binary format:
@@ -23,28 +8,30 @@ public class _190 {
238
* 0011,1001,0111,1000,0010,1001,0100,0000
249
* The most right side digit shifted to the most left side, the 2nd right side digit shifted to the 2nd left side, so forth..*/
2510

26-
/**This post: http://stackoverflow.com/questions/2811319/difference-between-and
11+
/**
12+
* This post: http://stackoverflow.com/questions/2811319/difference-between-and
2713
* gives a good explanation between logical right shift: ">>>" and arithmetic right shift: ">>".
2814
* Basically, ">>" preserves the most left bit and treats it as the sign for this number,
2915
* e.g. -2 represented in 8 bits is 11111110, thus -2 >> 1 will become 11111111, i.e. -1
3016
* notice its sign bit (the most left one bit) is preserved
3117
* However, logical right shift ">>>" doesn't care about the first bit on the most left,
3218
* it simply shifts every bit to the right.
33-
* e.g. -2 >>> 1 would become 1111111111111111111111111111111, i.e. 2147483647*/
19+
* e.g. -2 >>> 1 would become 1111111111111111111111111111111, i.e. 2147483647
20+
*/
3421

35-
public static class Solution1 {
36-
// you need treat n as an unsigned value
37-
public int reverseBits(int n) {
38-
int res = 0;
39-
for (int i = 0; i < 32; i++) {
40-
res += n & 1;//get the most right bit each time
41-
n >>>= 1;//do UN-signed right shift by 1 each time
42-
if (i < 31) {
43-
res <<=
44-
1;//shift this number to the left by 1 each time, so that eventually, this number is reversed
45-
}
22+
public static class Solution1 {
23+
// you need treat n as an unsigned value
24+
public int reverseBits(int n) {
25+
int res = 0;
26+
for (int i = 0; i < 32; i++) {
27+
res += n & 1;//get the most right bit each time
28+
n >>>= 1;//do UN-signed right shift by 1 each time
29+
if (i < 31) {
30+
res <<=
31+
1;//shift this number to the left by 1 each time, so that eventually, this number is reversed
32+
}
33+
}
34+
return res;
4635
}
47-
return res;
48-
}
4936
}
5037
}

0 commit comments

Comments
 (0)