Palindrome Number Problem and Solution

1. Introduction

The "Palindrome Number" problem involves determining whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. This problem tests the ability to manipulate numbers and check for reversibility.

2. Solution in C++

#include <iostream>
using namespace std;

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

// Example usage
int main() {
    int num = 121;
    cout << boolalpha << "Is Palindrome: " << isPalindrome(num) << endl;
    return 0;
}

Output:

Is Palindrome: true

Explanation:

1. isPalindrome function checks if a number is a palindrome.

2. Negative numbers and numbers ending with 0 are not palindromes.

3. The function reverses half of the number and compares it with the other half.

4. If the two halves are equal, or the reversed half is equal to the original half without its last digit, the number is a palindrome.

3. Solution in Java

public class PalindromeNumber {
    public static boolean isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) return false;
        int revertedNumber = 0;
        while (x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber / 10;
    }

    // Example usage
    public static void main(String[] args) {
        int num = 121;
        System.out.println("Is Palindrome: " + isPalindrome(num));
    }
}

Output:

Is Palindrome: true

Explanation:

1. Similar to the C++ solution, isPalindrome in Java checks if a number is a palindrome.

2. It handles negative numbers and those ending with 0.

3. Reverses half of the number and compares it to the other half.

4. Returns true if the number is a palindrome.

4. Solution in Python

def is_palindrome(x):
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
    reverted_number = 0
    while x > reverted_number:
        reverted_number = reverted_number * 10 + x % 10
        x //= 10
    return x == reverted_number or x == reverted_number // 10

# Example usage
num = 121
print("Is Palindrome:", is_palindrome(num))

Output:

Is Palindrome: True

Explanation:

1. The Python function is_palindrome follows a similar approach.

2. Checks for negatives and numbers ending with 0.

3. It reverses half of the number and compares it with the first half.

4. Returns true if it's a palindrome.


Comments