Easy Math ⭐ Popular Interview

Palindrome Number Without String Conversion (Python, C, JS)

Problem Statement

Given integer x, return true if it is a palindrome (reads same forwards and backwards) without converting to string.

Example
Input: x = 121
Output: true
Time Complexity
O(log n)
Space Complexity
O(1)

The Intuition

Revert only the second half of the number using % 10 and // 10. Compare it with the first half.

Solution Code

def isPalindrome(x):
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
    rev = 0
    while x > rev:
        rev = rev * 10 + x % 10
        x //= 10
    return x == rev or x == rev // 10
bool isPalindrome(int x) {
    if (x < 0 || (x % 10 == 0 && x != 0)) return false;
    int rev = 0;
    while (x > rev) { rev = rev * 10 + x % 10; x /= 10; }
    return x == rev || x == rev / 10;
}
function isPalindrome(x) {
    if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
    let rev = 0;
    while (x > rev) { rev = rev * 10 + x % 10; x = Math.floor(x / 10); }
    return x === rev || x === Math.floor(rev / 10);
}

Frequently Asked Questions

Q: Why reverse only half?
Reversing the full integer could overflow a 32-bit signed integer in C/Java. Stopping at the midpoint avoids this.

Practice These Problems in a Real Curriculum

DoxaTech Hub's 10-month programme covers Data Structures, Algorithms, Python, C, SQL, and Full-Stack Development through 40 weeks of real, graded projects.

Get Started → More Problems