Palindrome Number
Problem Statement
Section titled “Problem Statement”Given an integer x, return true if x is a palindrome, and false otherwise.
A palindrome reads the same forwards and backwards.
Examples
Section titled “Examples”| Input | Output | Explanation |
|---|---|---|
121 | true | Reads as 121 from left to right and right to left |
-121 | false | Reads as -121 forward but 121- backward |
10 | false | Reads as 01 from right to left |
Constraints
Section titled “Constraints”-2^31 <= x <= 2^31 - 1
Real-World Applications
Section titled “Real-World Applications”Complexity Comparison
Section titled “Complexity Comparison”| Approach | Time | Space | Notes |
|---|---|---|---|
| Without String (math) | O(log n) | O(1) | n = number of digits; no string allocation |
| With String | O(n) | O(n) | Converts integer to string; straightforward but uses extra memory |
Which approach should you learn first?
Section titled “Which approach should you learn first?”- Pick Without String if you want the strongest interview answer.
- Pick With String if you want the easiest version to understand before optimizing.
Approach 1: Without String (Recommended)
Section titled “Approach 1: Without String (Recommended)”Reverse the entire integer mathematically and compare it to the original. Early-exit for negative numbers and numbers ending in zero (except 0 itself).
Think of this as rebuilding the number from right to left. If the rebuilt number matches the original one, the digits were symmetrical.
Step-by-step Example
Section titled “Step-by-step Example”Input: x = 121
| Iteration | originalX | lastDigit | numReversed |
|---|---|---|---|
| Start | 121 | — | 0 |
| 1 | 12 | 1 | 1 |
| 2 | 1 | 2 | 12 |
| 3 | 0 | 1 | 121 |
121 == 121 → true ✓
Input: x = -121
Negative → return false immediately ✓
Input: x = 10
10 % 10 == 0 (ends in zero, non-zero) → return false immediately ✓
Animated walkthrough
Use Next or Autoplay to watch digits move from the original number into the reversed number until both can be compared.
Pseudocode
Section titled “Pseudocode”function isPalindrome(x): if x < 0: return false if x == 0: return true if x % 10 == 0: return false original = x reversed = 0 while x > 0: lastDigit = x % 10 reversed = reversed * 10 + lastDigit x = x / 10 return original == reversedSolution Code
Section titled “Solution Code”def is_palindrome(x: int) -> bool: if x < 0: return False if x == 0: return True if x % 10 == 0: return False num_reversed = 0 original_x = x while original_x > 0: last_digit = original_x % 10 num_reversed = num_reversed * 10 + last_digit original_x //= 10 return x == num_reversed
print(is_palindrome(121)) # Trueprint(is_palindrome(-121)) # Falseprint(is_palindrome(10)) # False#include <iostream>
bool isPalindrome(int x) { if (x < 0) { return false; } if (x == 0) { return true; } if (x % 10 == 0) { return false; } long long numReversed = 0; int originalX = x; while (originalX > 0) { int lastDigit = originalX % 10; numReversed = numReversed * 10 + lastDigit; originalX /= 10; } return x == numReversed;}
int main() { std::cout << std::boolalpha; std::cout << isPalindrome(121) << std::endl; // true std::cout << isPalindrome(-121) << std::endl; // false std::cout << isPalindrome(10) << std::endl; // false return 0;}public class Palindrome { public static boolean isPalindrome(int x) { if (x < 0) { return false; } if (x == 0) { return true; } if (x % 10 == 0) { return false; } int numReversed = 0; int originalX = x; while (originalX > 0) { int lastDigit = originalX % 10; numReversed = numReversed * 10 + lastDigit; originalX /= 10; } return x == numReversed; }
public static void main(String[] args) { System.out.println(isPalindrome(121)); // true System.out.println(isPalindrome(-121)); // false System.out.println(isPalindrome(10)); // false }}function isPalindrome(x) { if (x < 0) { return false; } if (x === 0) { return true; } if (x % 10 === 0) { return false; } let numReversed = 0; let originalX = x; while (originalX > 0) { const lastDigit = originalX % 10; numReversed = numReversed * 10 + lastDigit; originalX = Math.floor(originalX / 10); } return x === numReversed;}
console.log(isPalindrome(121)); // trueconsole.log(isPalindrome(-121)); // falseconsole.log(isPalindrome(10)); // falsefn is_palindrome(x: i32) -> bool { if x < 0 { return false; } if x == 0 { return true; } if x % 10 == 0 { return false; } let mut num_reversed = 0; let mut original_x = x; while original_x > 0 { let last_digit = original_x % 10; num_reversed = num_reversed * 10 + last_digit; original_x /= 10; } x == num_reversed}
fn main() { println!("{}", is_palindrome(121)); // true println!("{}", is_palindrome(-121)); // false println!("{}", is_palindrome(10)); // false}package main
import "fmt"
func isPalindrome(x int) bool { if x < 0 { return false } if x == 0 { return true } if x%10 == 0 { return false } numReversed := 0 originalX := x for originalX > 0 { lastDigit := originalX % 10 numReversed = numReversed*10 + lastDigit originalX /= 10 } return x == numReversed}
func main() { fmt.Println(isPalindrome(121)) // true fmt.Println(isPalindrome(-121)) // false fmt.Println(isPalindrome(10)) // false}Approach 2: With String
Section titled “Approach 2: With String”Convert the integer to a string and compare it to its reverse.
This version is easy to read because it turns the problem into a string comparison. The trade-off is extra memory.
Step-by-step Example
Section titled “Step-by-step Example”Input: x = 121
str(121) → "121" → reversed → "121" → equal → true ✓
Input: x = -121
str(-121) → "-121" → reversed → "121-" → not equal → false ✓
Input: x = 10
str(10) → "10" → reversed → "01" → not equal → false ✓
Pseudocode
Section titled “Pseudocode”function isPalindrome(x): str_x = str(x) return str_x == reverse(str_x)Solution Code
Section titled “Solution Code”def is_palindrome(x: int) -> bool: str_x = str(x) return str_x == str_x[::-1]
print(is_palindrome(121)) # Trueprint(is_palindrome(-121)) # Falseprint(is_palindrome(10)) # False#include <iostream>#include <string>
bool isPalindrome(int x) { std::string strX = std::to_string(x); for (size_t i = 0; i < strX.length() / 2; i++) { if (strX[i] != strX[strX.length() - i - 1]) { return false; } } return true;}
int main() { std::cout << std::boolalpha; std::cout << isPalindrome(121) << std::endl; // true std::cout << isPalindrome(-121) << std::endl; // false std::cout << isPalindrome(10) << std::endl; // false return 0;}public class Palindrome { public static boolean isPalindrome(int x) { String strX = Integer.toString(x); int n = strX.length(); for (int i = 0; i < n / 2; i++) { if (strX.charAt(i) != strX.charAt(n - i - 1)) { return false; } } return true; }
public static void main(String[] args) { System.out.println(isPalindrome(121)); // true System.out.println(isPalindrome(-121)); // false System.out.println(isPalindrome(10)); // false }}function isPalindrome(x) { const strX = x.toString(); return strX === strX.split('').reverse().join('');}
console.log(isPalindrome(121)); // trueconsole.log(isPalindrome(-121)); // falseconsole.log(isPalindrome(10)); // falsefn is_palindrome(x: i32) -> bool { let str_x = x.to_string(); str_x == str_x.chars().rev().collect::<String>()}
fn main() { println!("{}", is_palindrome(121)); // true println!("{}", is_palindrome(-121)); // false println!("{}", is_palindrome(10)); // false}package main
import ( "fmt" "strconv")
func isPalindrome(x int) bool { strX := strconv.Itoa(x) for i := 0; i < len(strX)/2; i++ { if strX[i] != strX[len(strX)-i-1] { return false } } return true}
func main() { fmt.Println(isPalindrome(121)) // true fmt.Println(isPalindrome(-121)) // false fmt.Println(isPalindrome(10)) // false}Approach 3: Optimized Two-Pointer
Section titled “Approach 3: Optimized Two-Pointer”A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.
Pseudocode
Section titled “Pseudocode”function approach3(): // Implementation approach goes hereSolution Code
Section titled “Solution Code”"""Solution for Palindrome Number"""
def solve(): """Implementation for approach 3 of Palindrome Number""" pass
if __name__ == "__main__": print("Solution ready")#include <bits/stdc++.h>using namespace std;
// Solution for Palindrome Number// Approach 3: Implementation
int main() {{ // Main implementation goes here return 0;}}/** * Solution for Palindrome Number * Approach 3 */public class PalindromeNumberOptimized {{
public static void main(String[] args) {{ // Implementation goes here }}}}/** * Solution for Palindrome Number * Approach 3 */
function solve() {{ // Implementation goes here}}
module.exports = solve;/// Solution for Palindrome Number/// Approach 3
fn main() {{ println!("Solution implementation");}}package main
import "fmt"
// Solution for Palindrome Number// Approach 3
func main() {{ fmt.Println("Solution implementation")}}