7. Reverse Integer
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Bit Manipulation
- Time
- O(log(x)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a 32-bit signed integer, return the digits reversed; if the reversed value overflows the 32-bit signed range [-2^31, 2^31 - 1], return 0 instead.
Approach
- Extract digits one at a time using
% 10and build the reversed number by multiplying the running result by 10 each step. - Before each multiply-and-add, check whether the new result would exceed
INT_MAXor fall belowINT_MINusing the guardresult > INT_MAX / 10(and the boundary digit check). - This overflow detection works entirely in integer arithmetic — no 64-bit types or bit tricks needed — making it portable across every 32-bit signed platform.
- The loop naturally handles negative numbers because C++ integer division and modulo preserve the sign of the dividend.
#include <climits>
using namespace std;
class Solution {
public:
int reverse(int x) {
int result = 0;
while (x != 0) {
int digit = x % 10; // preserves sign for negative x
x /= 10;
// Overflow check before updating result:
// INT_MAX = 2147483647 → last digit bound is 7
// INT_MIN = -2147483648 → last digit bound is -8
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > 7))
return 0;
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && digit < -8))
return 0;
result = result * 10 + digit;
}
return result;
}
};
Time O(log x) — the number of digits in x Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <climits>
class Solution {
public:
int reverse(int x) {
int result=0;
while(x!=0){
int digit=x%10;
if(result>INT_MAX/10 || (result==INT_MAX/10 && digit>7))
return 0;
if(result<INT_MIN/10 || (result==INT_MIN/10 && digit<-8))
return 0;
result=result*10+digit;
x/=10;
}
return result;
}
};
// Time Complexity: O(log(x)) where x is the input integer
// Space Complexity: O(1) Time O(log(x) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.