Skip to content

Commit 35d57d0

Browse files
committed
feat: add palindrome number solution
1 parent de53245 commit 35d57d0

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

leetcode/palindrome-number/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Palindrome Number
2+
3+
## Description
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// solve without converting to string
2+
const isPalindrome = (x) => {
3+
if (x < 0) {
4+
return false;
5+
}
6+
7+
let reverse = 0;
8+
const original = x;
9+
10+
while (x > 0) {
11+
reverse = (reverse * 10) + (x % 10);
12+
x = Math.floor(x / 10);
13+
}
14+
15+
return original === reverse;
16+
};
17+
18+
// solve by converting to string
19+
const isPalindrome2 = (x) => x.toString() === [...x.toString()].reverse().join('');
20+
21+
module.exports = {
22+
isPalindrome,
23+
isPalindrome2,
24+
};
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const { isPalindrome, isPalindrome2 } = require('./solution');
2+
3+
describe('Palindrome Number', () => {
4+
const testCases = [
5+
{
6+
input: 121,
7+
output: true,
8+
},
9+
{
10+
input: -121,
11+
output: false,
12+
},
13+
{
14+
input: 10,
15+
output: false,
16+
},
17+
{
18+
input: -101,
19+
output: false,
20+
},
21+
];
22+
23+
it('should return a boolean type', () => {
24+
expect(typeof isPalindrome(121)).toBe('boolean');
25+
expect(typeof isPalindrome2(121)).toBe('boolean');
26+
});
27+
28+
it.each(testCases)('should return $output', (testCase) => {
29+
expect(isPalindrome(testCase.input)).toBe(testCase.output);
30+
expect(isPalindrome2(testCase.input)).toBe(testCase.output);
31+
});
32+
});

0 commit comments

Comments
 (0)