Problem 9

Abstract / Summary

Determine if a given integer reads the same backward as forward.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
12 lines | 238 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 61% (10+ million submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 7 | μ = 6.69 | σ = 1.26

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
63 links | 44 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 9: Palindrome Number'
Algo Engine 6 mins
LeetCode 9: Palindrome Number
YouTube video 'Leetcode | 9. Palindrome Number | Easy | Java Solution'
Developer Docs 5 mins
Leetcode | 9. Palindrome Number | Easy | Java Solution
YouTube video 'Palindrome Number - LeetCode #9 - Python, JavaScript, Java, C++'
CodingNinja 7 mins
Palindrome Number - LeetCode #9 - Python, JavaScript, Java, C++
YouTube video 'Palindrome Number - LeetCode 9 - Coding Interview Questions'
One Code Man 5 mins
Palindrome Number - LeetCode 9 - Coding Interview Questions
YouTube video 'Palindrome Number - Leetcode 9 - C++ Solution Explained'
CodeWithSamidha 7 mins
Palindrome Number - Leetcode 9 - C++ Solution Explained
YouTube video 'Palindrome Number Python Solution - LeetCode #9'
Professor Oakes 4 mins
Palindrome Number Python Solution - LeetCode #9
YouTube video 'How to Solve "9 Palindrome Number" on LeetCode? - Javascript'
Becoming A Better Dev (with David) 6 mins
How to Solve "9 Palindrome Number" on LeetCode? - Javascript
YouTube video 'DSA Phir se with Sumeet | Leetcode 9 | Palindrome number'
Pepcoding 3 mins
DSA Phir se with Sumeet | Leetcode 9 | Palindrome number
YouTube video 'Google Interview Question - Palindrome Number - LeetCode 9'
AlgoJS 4 mins
Google Interview Question - Palindrome Number - LeetCode 9
YouTube video 'Leetcode 9 - Palindrome Number (Java, Solution Explained)'
LC Bear 9 mins
Leetcode 9 - Palindrome Number (Java, Solution Explained)
YouTube video 'LeetCode 9 - Palindrome Number - C#'
LeadEngineer 10 mins
LeetCode 9 - Palindrome Number - C#
YouTube video '9. Palindrome Number | Leetcode | Math based | Fundamentals'
Coding with Tamilarasan 8 mins
9. Palindrome Number | Leetcode | Math based | Fundamentals
YouTube video 'Day 2: LeetCode Problem 9. Palindrome Number - Swift'
iOSxBank 5 mins
Day 2: LeetCode Problem 9. Palindrome Number - Swift
YouTube video 'LeetCode 9: Palindrome Number | Java Solution | Two-Pointer Technique'
Code Scribbler 6 mins
LeetCode 9: Palindrome Number | Java Solution | Two-Pointer Technique
YouTube video 'LeetCode 9: Palindrome Number | Python Solution | Two-Pointer Technique'
Code Scribbler 6 mins
LeetCode 9: Palindrome Number | Python Solution | Two-Pointer Technique
YouTube video 'LeetCode 9: Palindrome Number | C# Solution | Math and String Manipulation'
Code Scribbler 6 mins
LeetCode 9: Palindrome Number | C# Solution | Math and String Manipulation
YouTube video '9. Palindrome Number (Leetcode Easy)'
Programming Live with Larry 4 mins
9. Palindrome Number (Leetcode Easy)
YouTube video 'Palindrome Number | Leetcode 9 | Approach + Code with explanation.'
Pirai's Academy 7 mins
Palindrome Number | Leetcode 9 | Approach + Code with explanation.
YouTube video 'LeetCode: 9. Palindrome Number (Visualized)'
Code With Zi 6 mins
LeetCode: 9. Palindrome Number (Visualized)
YouTube video 'Palindrome Number - Leetcode 9'
King of Interviews 13 mins
Palindrome Number - Leetcode 9
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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