LeetCode #9 Palindrome Number Solution & Explanation

LeetCode Problem

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 a palindrome while 123 is not.
LeetCode #9 Examples
LeetCode #9 Constraints

Solution

When I first saw this problem, I thought it was really easy. I figured I could just reverse the entire string and compare it to the original, it seemed like a simple solution.

However, we should test it to ensure its correctness.

C# Solution

Solution1 (reverse the string and compare)

public class Solution {
    public bool IsPalindrome(int x) {
        string first = x.ToString();             //turn to string (easy to reverse)
        char[] charArr = first.ToCharArray();   //the original target
        char[] reverseArr = first.ToCharArray();   

        Array.Reverse(reverseArr );                 
     
        return charArr.SequenceEqual(reverseArr); //compare two array
    }
}

The solution of reversing the whole string and comparing it, it worked but it took too long.

So, I thought about other ways to do it and came up with a new approach. Instead of reversing the whole string, I decided to compare the characters one by one.

For example, I could compare the first character to the last character, the second character to the second to last character, and so on. This method seemed faster and more efficient, so I gave it a try.

Solution2 (reduce the time cost)

public class Solution {
    public bool IsPalindrome(int x) {
        string k = x.ToString();        
        
        for(int i=0;i<k.Length/2;i++)   
        {
            if(k[i] != k[k.Length-1-i]) 
            {
                return false;           // if any char not the same, return false
            }
        }
        return true;                    
    }
}

The reason for dividing the length of k by 2 is that for a palindrome number, the first half will be the same as the second half when read backwards. So, if we compare the first half to the second half and they are the same, we can conclude that the whole number is a palindrome.

Java Solution

Solution1 ➡ similar to C# solution2

class Solution {
    public boolean isPalindrome(int x) {
        String k = String.valueOf(x);
      
        for(int i=0;i<k.length()/2;i++)
        {
            if(k.charAt(i) != k.charAt(k.length()-1-i))
            {
                return false;
            }
        }
        return true;
    }
}

Python3 Solution

Solution1

class Solution:
    def isPalindrome(self, x: int) -> bool:
        return str(x)[::-1] == str(x);

Solution2

class Solution:
    def isPalindrome(self, x: int) -> bool:
        xx = str(x);
        ll = int(len(xx)/2);
        
        for i in range(ll):
            if(xx[i] != xx[-i-1]):
                return False;
        return True;

JavaScript Solution

Solution1

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    
    let text = x.toString();
    for(var i=0;i<text.length/2;i++)
    {
        if(text.charAt(i) != text.charAt(text.length-1-i))
        {
            return false;
        }

    }
    return true;
};

Conclusion

This is an easy problem for get the result, but we can think about how to reduce the time spent, like solution two (reduce number of the iteration).

.

"Writing code is not that hard, but write a good code is not that easy."
                                                                                                          Zyrastory

The problem link : Palindrome Number – LeetCode

See related advanced problem : Valid Palindrome

Technology Article

Latest Post

Leave a Reply

Your email address will not be published. Required fields are marked *