Skip to content

Commit b9f8170

Browse files
committed
Update solution 007 solution.js [JavaScript]
1 parent f0037f4 commit b9f8170

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {number} x
3+
* @return {number}
4+
*/
5+
6+
/**
7+
* First Way:将数字转化为字符串的处理
8+
*/
9+
var reverse = function(x) {
10+
const min = -Math.pow(2,31),max = Math.pow(2,31) - 1;
11+
let sign = 1;
12+
if(x < 0){
13+
sign = -sign;
14+
x = sign * x;
15+
}
16+
let a = x.toString();
17+
let len = a.length,b='';
18+
for(let i = len - 1;i >= 0;i--)b+=a[i];
19+
b = sign * Number(b);
20+
if(b > max || b < min) return 0;
21+
return b;
22+
};
23+
/**
24+
* Second Way: 弹出和推入数字
25+
*/
26+
let reverse = function(x) {
27+
let res = 0;
28+
while (x !== 0) {
29+
res = res * 10 + x % 10;
30+
x = x < 0 ? Math.ceil(x / 10) : Math.floor(x / 10);
31+
}
32+
return res < -(2**31) || res > 2**31 - 1 ? 0 : res;
33+
};

0 commit comments

Comments
 (0)