C++ 0009.cpp
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
return false;
string a = to_string(x);
string b = a;
reverse(b.begin(), b.end());
return a == b;
}
};
Difficulty
and has an acceptance rate of about 61% (10+ million submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a 32-bit integer reads the same forward and backward. It follows a clear, linear flow: reject obvious non-palindromes, transform the numeric value into a textual representation, reverse that representation, and finally compare the two strings for equality.
Key Steps
Rejecting negative values
if (x < 0)
return false;
A negative sign cannot be mirrored at the end of the number, so any negative input is immediately classified as non-palindromic. This early exit prevents further processing for values that are guaranteed to fail the palindrome test.
Converting the integer to a string
string a = to_string(x);
The integer is turned into its decimal character sequence. This step leverages the standard library conversion, which handles the full range of signed integers, including zero and the maximum positive value.
Creating a reversed copy
string b = a;
reverse(b.begin(), b.end());
A second string b is initialized as a copy of a. The std::reverse algorithm then in-place flips the order of characters, producing the mirror image of the original digit sequence.
Comparing the original and reversed strings
return a == b;
Equality of the two strings indicates that the digit order reads identically from left to right and from right to left. The boolean result of this comparison is returned directly.
Edge Cases Handled
When the input is zero, the conversion yields the string "0". Reversing this single-character string leaves it unchanged, so the comparison succeeds and the function returns true.
Single-digit positive numbers (for example, 7) also become one-character strings; the reversal does not alter them, resulting in a true outcome.
Numbers that end with a zero, such as 10 or 1200, generate strings with trailing zeros that become leading zeros after reversal ("01" or "0021"). Since the original strings lack those leading zeros, the equality test fails, correctly identifying them as non-palindromes.
Negative inputs are caught by the initial guard clause, ensuring they never reach the conversion stage.
Performance Optimizations Observed
The early return for negative numbers eliminates unnecessary work for half of the possible integer domain, saving both CPU cycles and memory allocations associated with string creation.
Using std::string and std::reverse from the standard library provides highly tuned implementations that operate directly on contiguous memory, minimizing overhead compared to manual character manipulation.
The algorithm avoids additional data structures beyond the two strings, keeping the memory footprint small and the execution path straightforward.
ELI5 - Simplified Explanation
Imagine you have a row of colored blocks that spell out a word. A palindrome is a special kind of word that looks exactly the same whether you read it from left to right or if you turn your head around and read it from right to left.
This code acts like a little helper who checks if a number is one of these special mirrors. First, the helper looks at the number to see if it is hiding behind a minus sign. If it has a minus sign, it is not a palindrome, so the helper shakes its head no.
Next, the helper takes the number and writes it down on a piece of paper. Then, it takes a second piece of paper and writes the same number down again, but it carefully flips the order so the last number becomes the first. Finally, the helper holds both pieces of paper side by side to see if they look exactly the same. If the two papers match, then the number is a palindrome.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||||
| WalkCCC | C++ | Python | Java | |||||||||||
| leetcode.ca | C++ | Python | C | Java | Rust | C# | JS | Go | PHP | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Python | Java | |||||||||||
| github | AdelDaniel | Dart | ||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| fengvyi | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| lzl124631x | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| muhammadfarhankt | Go | |||||||||||||
| pruthvikp | Python | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| AdelDaniel | Dart | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| fengvyi | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| lzl124631x | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| muhammadfarhankt | Go | |||||||||||||
| pruthvikp | Python | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1: Two Sum
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality