-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path7-reverse-integer.js
55 lines (34 loc) · 1.07 KB
/
7-reverse-integer.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
/*
Author :- Rishabh Jain <contact@rishabh1403.com>
Solution for :- https://leetcode.com/problems/reverse-integer/
blog for this code :- https://rishabh1403.com/leetcode-solution-of-reverse-integer-in-javascript
youtube video :- https://www.youtube.com/watch?v=cIBwTqjh6VQ
*/
// string based method
var reverse = function (x) {
const reversedInt = parseInt(Math.abs(x).toString().split('').reverse().join(''));
if (reversedInt > 2 ** 31) return 0;
return reversedInt * Math.sign(x);
};
// string based method without explicit type casting
var reverse = function (x) {
const reversedInt = Math.abs(x).toString().split('').reverse().join('');
if (reversedInt > 2 ** 31) return 0;
return reversedInt * Math.sign(x);
};
// integer based method
var reverse = function (x) {
const isNegative = x < 0 ? true : false;
if (isNegative) {
x = x * -1;
}
let reversed = 0;
while (x > 0) {
reversed = (reversed * 10) + (x % 10);
x = parseInt(x / 10);
}
if (reversed > 2 ** 31) {
return 0;
}
return isNegative ? reversed * -1 : reversed;
};