check if number is palindrome in typescript

To check if a number is a palindrome, we need to convert it to a string, reverse the string, and then compare it with the original string to see if they are equal. One way to achieve this is by writing a function as follows:

index.ts
function isPalindrome(num: number): boolean {
  const strNum = num.toString();
  const reversedStr = strNum.split('').reverse().join('');
  return strNum === reversedStr;
}
173 chars
6 lines

We first convert the number to a string using the toString() method, and then reverse the string by converting it into an array using the split('') method, reversing the array using the reverse() method, and then joining the reversed array back into a string using the join('') method. Finally, we use the === operator to check if the original string is equal to the reversed string, and return true or false accordingly.

gistlibby LogSnag