File tree Expand file tree Collapse file tree 4 files changed +45
-13
lines changed
solution/0100-0199/0190.Reverse Bits Expand file tree Collapse file tree 4 files changed +45
-13
lines changed Original file line number Diff line number Diff line change 4848<!-- 这里可写当前语言的特殊实现逻辑 -->
4949
5050``` 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
5258```
5359
5460### ** Java**
5561
5662<!-- 这里可写当前语言的特殊实现逻辑 -->
5763
5864``` 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+ }
6076```
6177
6278### ** ...**
Original file line number Diff line number Diff line change 4545### ** Python3**
4646
4747``` 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
4955```
5056
5157### ** Java**
5258
5359``` 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+ }
5571```
5672
5773### ** ...**
Original file line number Diff line number Diff line change @@ -2,10 +2,10 @@ public class Solution {
22 // you need treat n as an unsigned value
33 public int reverseBits (int n ) {
44 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 ;
78 }
8- res |= (n &1 );
99 return res ;
1010 }
1111}
Original file line number Diff line number Diff line change 11class 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