# Check if a number is a palindrome using JavaScript

A number is a palindrome if its reversion is equal to the original number:

For example:

```terminal```121 is a palindrome
123 is not

3112113 is a palindrome
3112114 is not

-121 is not a palindrome, because if you revert it, you get 121-
``````

In JavaScript you can find if a number is a palindrome as follows:

```javascript```const isPalindrome = n => {

return n.toString() === n.toString().split('').reverse().join('')

}
``````

But what if you couldn't transform the number into a string?

```javascript```const isPalindrome = n => {

let x = n, y = 0

// E.g. n = 125
// 1. x = 12 y = 5
// 2. x = 1  y = 52
// 3. x = 0  y = 521
while(x > 0){

y = (y * 10) + 10 * (x/10 % 1).toFixed(2)
x = Math.floor(x/10)

}

return n === y

}
``````

## Optional

You could improve the previous solution by breaking the loop if you find any asymmetry:

```javascript```const isPalindrome = n => {

let x = n, y = 0, length_n, length_y

// E.g. n = 125
// 1. x = 12 y = 5
// 2. x = 1  y = 52
// 3. x = 0  y = 521
while(x > 0){

y = (y * 10) + 10 * (x/10 % 1).toFixed(2)
x = Math.floor(x/10)

// You can break the loop if n doesn't start with y
// No need to wait until the end of the loop
length_n = parseInt(Math.log10(n)) + 1
length_y = parseInt(Math.log10(y)) + 1

if(y !== Math.floor(n/(10 ** (length_n - length_y))))
break

}

return n === y

}
`````` Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.