EN
TypeScript - check if number is palindrome
0 points
In this short article, we would like to show how to check if a number is a palindrome using TypeScript.
Definition:
Palindromes are characters sequence that we can read the same backward as forward (e.g.
121
,12321
).
The solution shown in the article allows you to check if the integer and floating-point numbers are palindromes.
Practical example:
xxxxxxxxxx
1
const isPalindrome = (input: number): boolean => {
2
const string = input.toString();
3
for (let i = 0, j = string.length - 1; i < j; ++i, --j) {
4
if (string[i] !== string[j]) {
5
return false;
6
}
7
}
8
return true;
9
};
10
11
12
// Usage example:
13
14
console.log(isPalindrome(12321)); // true
15
console.log(isPalindrome(12.21)); // true
16
console.log(isPalindrome(454)); // true
17
console.log(isPalindrome(123)); // false
18
console.log(isPalindrome(3.14)); // false
Output:
xxxxxxxxxx
1
true
2
true
3
true
4
false
5
false