File tree 4 files changed +45
-13
lines changed
solution/0100-0199/0190.Reverse Bits
4 files changed +45
-13
lines changed Original file line number Diff line number Diff line change 48
48
<!-- 这里可写当前语言的特殊实现逻辑 -->
49
49
50
50
``` python
51
-
51
+ class Solution :
52
+ def reverseBits (self , n : int ) -> int :
53
+ res = 0
54
+ for i in range (32 ):
55
+ res |= ((n & 1 ) << (31 - i))
56
+ n >>= 1
57
+ return res
52
58
```
53
59
54
60
### ** Java**
55
61
56
62
<!-- 这里可写当前语言的特殊实现逻辑 -->
57
63
58
64
``` java
59
-
65
+ public class Solution {
66
+ // you need treat n as an unsigned value
67
+ public int reverseBits (int n ) {
68
+ int res = 0 ;
69
+ for (int i = 0 ; i < 32 && n != 0 ; ++ i) {
70
+ res |= ((n & 1 ) << (31 - i));
71
+ n >>> = 1 ;
72
+ }
73
+ return res;
74
+ }
75
+ }
60
76
```
61
77
62
78
### ** ...**
Original file line number Diff line number Diff line change 45
45
### ** Python3**
46
46
47
47
``` python
48
-
48
+ class Solution :
49
+ def reverseBits (self , n : int ) -> int :
50
+ res = 0
51
+ for i in range (32 ):
52
+ res |= ((n & 1 ) << (31 - i))
53
+ n >>= 1
54
+ return res
49
55
```
50
56
51
57
### ** Java**
52
58
53
59
``` java
54
-
60
+ public class Solution {
61
+ // you need treat n as an unsigned value
62
+ public int reverseBits (int n ) {
63
+ int res = 0 ;
64
+ for (int i = 0 ; i < 32 && n != 0 ; ++ i) {
65
+ res |= ((n & 1 ) << (31 - i));
66
+ n >>> = 1 ;
67
+ }
68
+ return res;
69
+ }
70
+ }
55
71
```
56
72
57
73
### ** ...**
Original file line number Diff line number Diff line change @@ -2,10 +2,10 @@ public class Solution {
2
2
// you need treat n as an unsigned value
3
3
public int reverseBits (int n ) {
4
4
int res = 0 ;
5
- for (int i = 0 ; i < 31 ; i ++, n >>=1 , res <<=1 ) {
6
- res |= (n &1 );
5
+ for (int i = 0 ; i < 32 && n != 0 ; ++i ) {
6
+ res |= ((n & 1 ) << (31 - i ));
7
+ n >>>= 1 ;
7
8
}
8
- res |= (n &1 );
9
9
return res ;
10
10
}
11
11
}
Original file line number Diff line number Diff line change 1
1
class Solution :
2
- # @param n, an integer
3
- # @return an integer
4
- def reverseBits ( self , n ):
5
- B = bin ( n )
6
- B = ( B [ 2 :]. rjust ( 32 , "0" ))[:: - 1 ]
7
- return int ( B , 2 )
2
+ def reverseBits ( self , n : int ) -> int :
3
+ res = 0
4
+ for i in range ( 32 ):
5
+ res |= (( n & 1 ) << ( 31 - i ) )
6
+ n >>= 1
7
+ return res
You can’t perform that action at this time.
0 commit comments