Skip to content

Commit 7c9a70f

Browse files
authored
Merge pull request #57 from Mcnwork2018/dev
Update solution 007 solution.js [JavaScript]
2 parents e005224 + 5ac087b commit 7c9a70f

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

solution/007.Reverse Integer/Solution.js

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
/**
2+
* @param {number} x
3+
* @return {number}
4+
*/
15
const reverse1 = function(x){
26
let s = String(x);
37
let isNegative = false;
@@ -12,4 +16,36 @@ const reverse = function(x){
1216
let result = parseInt(x.toString().split('').reverse().join(''));
1317
if(result > Math.pow(2,31) - 1 || -result < Math.pow(-2,31)) return 0;
1418
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+
};

0 commit comments

Comments
 (0)