Problem 7

Abstract / Summary

Given an integer, return its digits reversed keeping it within 32-bit signed integer range.

Note

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

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;
    }
};
28 lines | 599 bytes | submitted August 8, 2023 | GitHub   4% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 32% (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 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 == 0 ensures 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 -123 to -321.
  • Maximum Positive Value - The overflow check (result > INT_MAX) catches cases where the reversed digits would exceed 2,147,483,647, for example reversing 1534236469 would produce a value larger than INT_MAX, leading to a zero return.
  • Minimum Negative Value - The conversion to double and subsequent unsigned storage correctly handle INT_MIN (-2147483648). The magnitude becomes 2147483648, 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 int for n eliminates 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 double leverages 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.
written by openai gpt

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.

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 = 3 | μ = 3.79 | σ = 1.65

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 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++
59 links | 41 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Reverse Integer - Bit Manipulation - Leetcode 7 - Python'
NeetCode 14 mins
Reverse Integer - Bit Manipulation - Leetcode 7 - Python
YouTube video 'Reverse Integer | LeetCode 7 | Top Interview | Facebook Google Apple Amazon'
Naresh Gupta 11 mins
Reverse Integer | LeetCode 7 | Top Interview | Facebook Google Apple Amazon
YouTube video 'Reverse Integer - LeetCode 7 - LeetCode Daily Challenge'
One Code Man 4 mins
Reverse Integer - LeetCode 7 - LeetCode Daily Challenge
YouTube video 'DSA Phir se with Sumeet | Leetcode 7 | Reverse Integer'
Pepcoding 6 mins
DSA Phir se with Sumeet | Leetcode 7 | Reverse Integer
YouTube video 'Reverse Integer Python Solution - LeetCode #7'
Professor Oakes 5 mins
Reverse Integer Python Solution - LeetCode #7
YouTube video 'Reverse Integer | LeetCode 7 | Easy'
Code And Coffee 14 mins
Reverse Integer | LeetCode 7 | Easy
YouTube video 'LeetCode: 7. Reverse Integer (Visualized)'
Code With Zi 6 mins
LeetCode: 7. Reverse Integer (Visualized)
YouTube video 'LeetCode | #7 | Reverse Integer (Java)'
Anish Learns To Code 17 mins
LeetCode | #7 | Reverse Integer (Java)
YouTube video 'Reverse Integer - Google Interview Questions - LeetCode 7 Solution - C++'
nexTRIE 9 mins
Reverse Integer - Google Interview Questions - LeetCode 7 Solution - C++
YouTube video 'Leetcode 7: Reverse Integer in Telugu | String, Math Approach | Python DSA | srkcodes'
Srk Codes 6 mins
Leetcode 7: Reverse Integer in Telugu | String, Math Approach | Python DSA | srkcodes
YouTube video 'Reverse Integer - LeetCode #7 - C++'
Sean Chuah 6 mins
Reverse Integer - LeetCode #7 - C++
YouTube video 'Leetcode 7 - Reverse Integer (Java, Solution Explained)'
LC Bear 9 mins
Leetcode 7 - Reverse Integer (Java, Solution Explained)
YouTube video 'Leetcode 7 - Reverse Integer JavaScript'
Chuck's Resume 23 mins
Leetcode 7 - Reverse Integer JavaScript
YouTube video '7. Reverse Integer (Leetcode Easy)'
Programming Live with Larry 9 mins
7. Reverse Integer (Leetcode Easy)
YouTube video '148. Leetcode 7. Reverse Integer : Javascript'
Web Fusion with Bharadwaj 16 mins
148. Leetcode 7. Reverse Integer : Javascript
YouTube video '7. Reverse Integer | Java | Leetcode | Number Theory | Fundamentals'
Coding with Tamilarasan 10 mins
7. Reverse Integer | Java | Leetcode | Number Theory | Fundamentals
YouTube video '181. Leetcode 7. Reverse Integer : JAVA'
Web Fusion with Bharadwaj 14 mins
181. Leetcode 7. Reverse Integer : JAVA
YouTube video 'Reverse Integer | Leetcode 7 | Approach + Code with explanation.'
Pirai's Academy 5 mins
Reverse Integer | Leetcode 7 | Approach + Code with explanation.
YouTube video 'ASMR Leetcode #7 : Reverse Integer Python solution'
ExtremeProgrammer 4 mins
ASMR Leetcode #7 : Reverse Integer Python solution
YouTube video 'Day 334: LeetCode Problem 7. Reverse Integer - Swift'
iOSxBank 10 mins
Day 334: LeetCode Problem 7. Reverse Integer - Swift
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

19 easy 42 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