1
1
package com .fishercoder .solutions ;
2
2
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
-
18
3
public class _190 {
19
4
/**delimiting the binary string into 4 bits array will make it easier to see/visualize:
20
5
* original binary format:
@@ -23,28 +8,30 @@ public class _190 {
23
8
* 0011,1001,0111,1000,0010,1001,0100,0000
24
9
* The most right side digit shifted to the most left side, the 2nd right side digit shifted to the 2nd left side, so forth..*/
25
10
26
- /**This post: http://stackoverflow.com/questions/2811319/difference-between-and
11
+ /**
12
+ * This post: http://stackoverflow.com/questions/2811319/difference-between-and
27
13
* gives a good explanation between logical right shift: ">>>" and arithmetic right shift: ">>".
28
14
* Basically, ">>" preserves the most left bit and treats it as the sign for this number,
29
15
* e.g. -2 represented in 8 bits is 11111110, thus -2 >> 1 will become 11111111, i.e. -1
30
16
* notice its sign bit (the most left one bit) is preserved
31
17
* However, logical right shift ">>>" doesn't care about the first bit on the most left,
32
18
* 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
+ */
34
21
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 ;
46
35
}
47
- return res ;
48
- }
49
36
}
50
37
}
0 commit comments