Palindrome Number
Easy
Math
Problem
Given an integer x, return true if it is a palindrome (reads the same forwards and backwards). Negative numbers are not palindromes.
Example 1
Input: x = 121
Output: true
Example 2
Input: x = -121
Output: false
Example 3
Input: x = 10
Output: false
Constraints
- −2³¹ ≤ x ≤ 2³¹ − 1
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
Python
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
return str(x) == str(x)[::-1]
Java
class Solution {
public boolean isPalindrome(int x) {
// Negatives and any number ending in 0 (besides 0 itself) can't be palindromes.
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
// Even length → x == reversed; odd length → middle digit is in reversed,
// so drop it with reversed / 10.
return x == reversed || x == reversed / 10;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Palindrome Number interactively → ← All solutions