Solving JS Algorithm Problem: Palindrome-Number

Perezchristian
2 min readMar 10, 2021

The problem states the following:

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.

Example 1:

Input: x = 121
Output: true

Solution:

Step #1: I first converted the isPalindrome method to be written in ES6 notation.

const isPalindrome = (x) => {
};

Step #2: We build out our if statement by typing the following:

if (x<0 || x%10 === 0 && x !== 0) return false;

This reads if x is less than 0 or if x is divisible by 10 and the total is equal to 0 and if x is not equal to 0, return false.

This is because in any of these cases we know that it would be outright false.

For example if x = 10, it will read as 01 from right to left. Therefore it is not a palindrome.

Step #3: We need to assign a variable for the reverse amount set to 0 and a new variable to express the number x.

let reverse = 0;
let num = x;

Step #4: We use the while statement loop that will execute if the conditions we define are met.

while(num > reverse) {
reverse = num%10 + reverse*10;
num = parseInt(num/10);
}

if num is greater than 0, we will redefine what reverse will be by setting it equal to the num divided by 10 (with the remainder present) plus the reverse amount multiplied by 10 (12.1 for our example).

we then redefine what num will be by parsing the num amount divided by 10 (12.1 for our example) and then using the parseInt() built-in function to combine the amount and make it one single string.

Step #5: Lastly we define our overall output to print when num is equal to reverse or if num is equal the reverse amount divided by 10 with any remainder and then using the parseInt() function to combine the amount to make it one single string.

return (num === reverse || num === parseInt(reverse/10));

For this problem, 121 is a palindrome and the output would return true within our terminal.

--

--

Perezchristian

Flatiron School Graduate with finance, budget, and tax experience.