DEV Community

kiranojhanp
kiranojhanp

Posted on

Leetcode Palindrome Number - Fastest solution 100%

Image description

This method is MUCH FASTER than other methods which convert the number to an Array and then reverse it and join it again.

Code

Typescript

function flipInt(num: number): number {
  let remainder: number,
    value: number = 0;
  while (num > 0) {
    remainder = num % 10;
    value = value * 10 + remainder;
    num = (num / 10) | 0;
  }
  return value;
}

function isPalindrome(x: number): boolean {
  return x >= 0 ? flipInt(x) === x : false;
}
Enter fullscreen mode Exit fullscreen mode

Javascript

function flipInt(num) {
  let remainder,
    value = 0;
  while (num > 0) {
    remainder = num % 10;
    value = value * 10 + remainder;
    num = (num / 10) | 0;
  }
  return value;
}

function isPalindrome(x) {
  return x >= 0 ? flipInt(x) === x : false;
}
Enter fullscreen mode Exit fullscreen mode

Inspired from:
https://medium.com/@ManBearPigCode/how-to-reverse-a-number-mathematically-97c556626ec6

Top comments (0)