-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
57 lines (50 loc) · 1.1 KB
/
res.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Reverse digits of an integer.
*
* Example1: x = 123, return 321
* Example2: x = -123, return -321
*
* Note:
* The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
*
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-02-21 21:25:59
* @version $Id$
*/
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let res = 0,
abs = Math.abs(x),
negative = abs === x? false:true;
while (abs>0) {
let currentVal = abs % 10;
res = res*10 + currentVal;
abs = Number.parseInt(abs/10);
}
if (res > Math.pow(2, 31)) {
return 0;
} else if (negative) {
return -res;
}
return res;
};
// Another solution wrote in Java
//
// public int reverse(int x)
// {
// int result = 0;
// while (x != 0)
// {
// int tail = x % 10;
// int newResult = result * 10 + tail;
// if ((newResult - tail) / 10 != result)
// { return 0; }
// result = newResult;
// x = x / 10;
// }
// return result;
// }