-
Notifications
You must be signed in to change notification settings - Fork 1
/
reverseInteger.js
57 lines (43 loc) · 1.02 KB
/
reverseInteger.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
//Slower
function reverseInterger(num) {
let numStr = num.toString();
let sIndex = numStr.length - 1;
let eIndex = 0;
if(numStr[0] === "-") {
return parseInt("-" + strRev(numStr, sIndex, eIndex + 1));
}
if(numStr[numStr.length - 1] === "0") {
return parseInt(strRev(numStr, sIndex - 1, eIndex));
}
return parseInt(strRev(numStr, sIndex, eIndex));
}
function strRev(str, sIndex, eIndex) {
let result = "";
for(var i = sIndex; i >= eIndex; i--) {
result += str[i];
}
return result;
}
console.log(reverseInterger(120));
var num = 0;
console.log(Math.pow(2,32) - 1);
// Faster
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
var rev = "";
var a = x.toString().split("");
for (var i=a.length-1; i >= 0; i--) {
rev += a[i];
}
rev = parseInt(rev);
if (rev > Math.pow(2,31) - 1) {
return 0;
}
if(a[0] === "-") {
rev *= -1;
}
return rev;
};