C++ 0007.cpp
class Solution {
public:
int reverse(int x) {
if (x == 0)
return 0;
// cheating by using double instead of int64 (ca. 52 bits)
bool isNeg = x < 0;
unsigned int n;
if (isNeg)
n = -double(x);
else
n = +double(x);
double result = 0;
while (n > 0)
{
auto digit = n % 10;
n /= 10;
result = result * 10 + digit;
}
if (result > INT_MAX)
return 0;
return isNeg ? -result : +result;
}
};
Difficulty
and has an acceptance rate of about 32% (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 presented Solution::reverse method implements an integer reversal algorithm that accepts a 32-bit signed integer x and returns the digits of x in reverse order. The function explicitly handles the zero input, distinguishes sign, performs the reversal using arithmetic on an unsigned representation, and guards against overflow by checking the result against INT_MAX. The implementation relies on a double conversion to obtain an unsigned magnitude without invoking a larger integer type.
Key Steps
Zero-Value Shortcut
if (x == 0)
return 0;
The function immediately returns for the trivial case where the input is zero, avoiding any further computation.
Sign Detection and Magnitude Extraction
bool isNeg = x < 0;
unsigned int n;
if (isNeg)
n = -double(x);
else
n = +double(x);
A boolean flag records whether the original number is negative. The magnitude is obtained by converting x to double, applying a unary minus for negative values, and storing the result in an unsigned 32-bit variable n. This conversion sidesteps the need for a 64-bit integer type while preserving the exact integer value for all inputs that fit in 32 bits.
Digit-by-Digit Reversal Loop
double result = 0;
while (n > 0)
{
auto digit = n % 10;
n /= 10;
result = result * 10 + digit;
}
The loop extracts the least-significant digit of n using the modulus operator, reduces n by a factor of ten, and builds the reversed number in result. The accumulator result is a double, which provides sufficient precision (approximately 52 bits) to hold any intermediate value that could arise from reversing a 32-bit integer.
Overflow Detection
if (result > INT_MAX)
return 0;
After the reversal, the function checks whether the computed value exceeds the maximum representable 32-bit signed integer. If it does, the specification dictates returning zero to signal overflow.
Restoring the Original Sign
return isNeg ? -result : +result;
Finally, the sign flag determines whether the reversed magnitude should be negated before returning. The unary plus is used for the positive branch to keep the expression symmetric.
Edge Cases Handled
The algorithm explicitly addresses several boundary conditions:
- Zero Input - The early return for
x == 0ensures that the function does not enter the reversal loop, which would otherwise be unnecessary. - Negative Numbers - By recording the sign before magnitude extraction and reapplying it at the end, the code correctly reverses numbers such as
-123to-321. - Maximum Positive Value - The overflow check (
result > INT_MAX) catches cases where the reversed digits would exceed2,147,483,647, for example reversing1534236469would produce a value larger thanINT_MAX, leading to a zero return. - Minimum Negative Value - The conversion to
doubleand subsequent unsigned storage correctly handleINT_MIN(-2147483648). The magnitude becomes2147483648, which fits within the 52-bit mantissa of a double, allowing the reversal process to proceed without loss of information.
Performance Optimizations
The implementation incorporates a few choices that reduce runtime overhead:
- Early Exit for Zero - By handling the zero case up front, the function avoids the cost of sign detection, conversion, and loop execution for the most common trivial input.
- Unsigned Loop Variable - Using an
unsigned intforneliminates the need for additional sign checks inside the reversal loop, allowing the compiler to generate tighter arithmetic instructions. - Double as Accumulator - Storing the intermediate result in a
doubleleverages the processor’s floating-point unit, which can often perform multiplication and addition faster than equivalent 64-bit integer operations on modern CPUs. The 52-bit mantissa comfortably accommodates any intermediate value that arises from reversing a 32-bit integer, so no extra range checks are required during the loop. - Single Pass Reversal - The while-loop processes each digit exactly once, achieving the minimal number of arithmetic operations needed to construct the reversed number. No auxiliary data structures (such as strings or vectors) are allocated, keeping memory usage low and avoiding cache pressure.
ELI5 - Simplified Explanation
Imagine there is a box labeled Solution that holds a special machine for backward playing. When you give the machine a number like one hundred twenty-three, it wants to turn it into three hundred twenty-one.
The machine starts by checking if the number is zero. If you give it nothing, it just gives you nothing back.
Next, it checks if the number is hiding a tiny minus sign, which means it is a negative number. It keeps the minus sign safe in a little pocket so it can be added back at the very end. It turns the number into a positive version to make the work easier.
The machine begins a spinning loop to take the number apart. It peeks at the very last digit of the number and moves it to a new pile. Then, it shrinks the original number by dividing it by ten, which pushes the next digit to the end so it can be grabbed next. It keeps doing this until there are no digits left in the original pile, all while growing the new number by multiplying it by ten each time a new digit lands.
After all the juggling, the machine does one final check to make sure the new number did not grow too big to fit inside its original container. If everything works perfectly, it looks in the pocket for that secret minus sign, puts it back if it was there, and hands the new backwards number to you.
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 | Java | C# | C | Rust | JS | Go | PHP | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| qiyuangong | Java | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| qiyuangong | Java | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 8: String to Integer (atoi)
- problem 190: Reverse Bits
- problem 2119: A Number After a Double Reversal
- problem 2442: Count Number of Distinct Integers After Reverse Operations
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- 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 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