-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path9-palindrome-number.js
65 lines (46 loc) · 1.05 KB
/
9-palindrome-number.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
58
59
60
61
62
63
64
65
/*
Author :- Rishabh Jain <[email protected]>
Solution for :- https://leetcode.com/problems/palindrome-number/
blog for this code :- https://rishabh1403.com/leetcode-solution-of-palindrome-number-in-javascript
youtube video :- https://youtu.be/7lCkkX3UAvU
*/
// string based implementation
var isPalindrome = function (x) {
return x == x.toString().split('').reverse().join('');
};
// number based implementation
var isPalindrome = function (x) {
const isNegative = x < 0 ? true : false;
if (isNegative) {
return false;
}
const temp = x;
let reversed = 0;
while (x > 0) {
reversed = (reversed * 10) + (x % 10);
x = parseInt(x / 10);
}
return reversed == temp;
};
// two pointer method
var isPalindrome = function (x) {
if (x < 0) {
return false;
}
if (x < 10) {
return true;
}
if (x % 10 === 0 && x !== 0) {
return false;
}
const str = String(x);
let i = 0, j = str.length - 1;
while (i < j) {
if (str[i] !== str[j]) {
return false;
}
i++;
j--;
}
return true;
};