Palindrome Number – Leetcode Solution

In this post, we are going to solve the 9. Palindrome Number problem of Leetcode. This problem 9. Palindrome Number is a Leetcode easy level problem. Let’s see code, 9. Palindrome Number – Leetcode Solution.

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.

Example 1 :


Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2 :


Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints

  • -231 <= x <= 231 - 1

Now, let’s see the code of 9. Palindrome Number – Leetcode Solution.

Palindrome Number – Leetcode Solution

9. Palindrome Number – Solution in Java

class Solution {
    public boolean isPalindrome(int x) {
        int org = x;
        int rev = 0;
        
        while(org > 0){
            int unit = org%10;
            rev = 10*rev+unit;
            org/=10;
        }
        
        return rev == x;
    }
}

9. Palindrome Number – Solution in C++

class Solution {
public:
    bool isPalindrome(int x) {
        int org = x;
        int rev = 0;
        
        while(org > 0){
            int unit = org%10;
            rev = 10*rev+unit;
            org/=10;
        }
        
        return rev == x;
    }
};

9. Palindrome Number – Solution in Python

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

Note: This problem 9. Palindrome Number is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

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