File tree Expand file tree Collapse file tree 1 file changed +37
-1
lines changed
solution/007.Reverse Integer Expand file tree Collapse file tree 1 file changed +37
-1
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } x
3
+ * @return {number }
4
+ */
1
5
const reverse1 = function ( x ) {
2
6
let s = String ( x ) ;
3
7
let isNegative = false ;
@@ -12,4 +16,36 @@ const reverse = function(x){
12
16
let result = parseInt ( x . toString ( ) . split ( '' ) . reverse ( ) . join ( '' ) ) ;
13
17
if ( result > Math . pow ( 2 , 31 ) - 1 || - result < Math . pow ( - 2 , 31 ) ) return 0 ;
14
18
return x > 0 ? result : - result ;
15
- }
19
+ }
20
+ /**
21
+ * author:mcn date:2018/10/25
22
+ */
23
+
24
+ /**
25
+ * First Way:将数字转化为字符串的处理
26
+ */
27
+ var reverse = function ( x ) {
28
+ const min = - Math . pow ( 2 , 31 ) , max = Math . pow ( 2 , 31 ) - 1 ;
29
+ let sign = 1 ;
30
+ if ( x < 0 ) {
31
+ sign = - sign ;
32
+ x = sign * x ;
33
+ }
34
+ let a = x . toString ( ) ;
35
+ let len = a . length , b = '' ;
36
+ for ( let i = len - 1 ; i >= 0 ; i -- ) b += a [ i ] ;
37
+ b = sign * Number ( b ) ;
38
+ if ( b > max || b < min ) return 0 ;
39
+ return b ;
40
+ } ;
41
+ /**
42
+ * Second Way: 弹出和推入数字
43
+ */
44
+ let reverse = function ( x ) {
45
+ let res = 0 ;
46
+ while ( x !== 0 ) {
47
+ res = res * 10 + x % 10 ;
48
+ x = x < 0 ? Math . ceil ( x / 10 ) : Math . floor ( x / 10 ) ;
49
+ }
50
+ return res < - ( 2 ** 31 ) || res > 2 ** 31 - 1 ? 0 : res ;
51
+ } ;
You can’t perform that action at this time.
0 commit comments