Link Search Menu Expand Document

9. Palindrome Number

Solution Code

C++

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
       
        int reverseNumber = 0;
       
        while(x > reverseNumber) {
            reverseNumber = (reverseNumber * 10) + (x % 10);
            x = x / 10;
        }
        
        return x == reverseNumber || x == reverseNumber / 10;
    }
};

Java

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;

        int reversedInteger = 0, lastDigit, temp;
        temp = x; // storing the original number to a temporary variable
        // Reversing the number
        while (temp != 0) {
            lastDigit = temp % 10;
            reversedInteger = reversedInteger * 10 + lastDigit;
            temp = temp / 10;
        }
        // checking if palindrome or not using condition
        if (reversedInteger == x)
            return true;
        else
            return false;
    }
}

Python

class Solution(object):
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False

        b = int(str(x) [::-1])
        
        if b == x:
            return True
            
        return False
class Solution:
    def isPalindrome(self, x: int) -> bool:
        x_str = str(x)
        left_idx = 0        
        right_idx = len(x_str) - 1
        
        while left_idx < right_idx:
            if x_str[left_idx] != x_str[right_idx]:
                return False
            
            left_idx += 1
            right_idx -= 1
            
        return True

© 2023. All rights reserved.