DSA: palindromeNumber

Niani Byrd
2 min readNov 30, 2021

We’ve talked about palindromes before, but how can we check if an integer is a palindrome? The process is a bit different.

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.

This problem can easily be solved if we reverse the number, then compare the reversed number with the given number.

First, we want to check if the number is negative. If it is, return false.

var isPalindrome = function(x) {
if (x < 0) {
return false;
}

Next, we want to store the given number x, in a variable. We’ll call this variable num. We have to create a variable because after we perform all of our operations, the value will change. When we’re finished we’ll use x to compare it with the variable (the reversed number).

var isPalindrome = function(x) {
// Base condition
if (x < 0) {
return false;
}
// Store the number in a variable
let number = x;
// This will store the reverse of the number
let reverse = 0;

After this is done, this is where we reverse the variable. To reverse, we’ll divide the number repeatedly until the number becomes zero.

var isPalindrome = function(x) {
// Base condition
if (x < 0) {
return false;
}
// Store the number in a variable
let number = x;
// This will store the reverse of the number
let reverse = 0;
while (number > 0) {
reverse = reverse * 10 + number % 10;
number = parseInt(number / 10);
}

Lastly, return true if the reverse number and given number are equal. We return false if otherwise.

var isPalindrome = function(x) {
// Base condition
if (x < 0) {
return false;
}
// Store the number in a variable
let number = x;
// This will store the reverse of the number
let reverse = 0;
while (number > 0) {
reverse = reverse * 10 + number % 10;
number = parseInt(number / 10);
}
return x === reverse;
};

Happy coding!

--

--