Number Palindrome

Problem Link : Number Palindrome


Problem Statement

You are given an integer n.
Determine whether it is a palindrome.

A number is a palindrome if it reads the same backward as forward.


Examples

Example 1:

Example 2:

Example 3:


Constraints


Intuition

A number is a palindrome if reversing its digits results in the same number.

To check this, we:

If both are equal, the number is a palindrome.


Approach

  1. Store the original number in a variable cpy.

  2. Initialize a variable rev = 0 to store the reversed number.

  3. Loop until n becomes 0:

    • Extract the last digit using n % 10.

    • Append it to the reversed number: rev = rev * 10 + digit.

    • Remove the last digit: n = n / 10.

  4. Finally, compare rev with the original number cpy.

If they are equal, return true; otherwise, return false.


Java Code

class Solution {
    public boolean isPalindrome(int n) {
        int rev = 0;
        int cpy = n;             // Store the original number
        while (n > 0) {
            int r = n % 10;      // Get the last digit
            rev = rev * 10 + r;  // Build the reversed number
            n /= 10;             // Remove last digit
        }
        return rev == cpy;       // Compare reversed with original
    }
}

Dry Run

Input: n = 121

Step 1:

Step 2:

Step 3:

Final Check:


Time Complexity


Space Complexity


Conclusion

This arithmetic approach to checking for a palindrome is both efficient and reliable, avoiding the need to convert the number to a string. It adheres to optimal time and space constraints and handles all valid positive integers within the given range.