Skip to content

Instantly share code, notes, and snippets.

@tawn33y
Last active September 2, 2022 15:27
Show Gist options
  • Save tawn33y/eec7a48263e0d82e528834d6f0e367d0 to your computer and use it in GitHub Desktop.
Save tawn33y/eec7a48263e0d82e528834d6f0e367d0 to your computer and use it in GitHub Desktop.
Solved (JS): Determine whether an integer is a palindrome

Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

  Input: 121
  Output: true

Example 2:

  Input: -121
  Output: false
  Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

  Input: 10
  Output: false
  Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

const isPalindrome = (x) => {
if (x < 0 || (x % 10 === 0 && x !== 0)) {
return false;
}
return x === reverse(x);
};
const reverse = (num) => {
let rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num = parseInt(num / 10, 10);
}
return rev;
};
@raghavprasad31
Copy link

what is parseInt?

@tawn33y
Copy link
Author

tawn33y commented Sep 2, 2022

@7761962082 The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

See more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

e.g.

const yearAsString = '2022';
const yearAsInt = parseInt(yearAsString, 10); // to base 10

console.log(yearAsInt); // => 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment