Reverse Integer

Reverse a 32-bit signed integer's digits — detect overflow before multiplying by 10.

Medium
Time O(log n) Space O(1)
LeetCode
3 min read
math overflow

Problem#

Reverse the digits of a 32-bit signed integer. If the result overflows [-2^31, 2^31 - 1], return 0.

Examples#

  • 123321; -123-321.
  • 12021; 15342364690 (overflow).

Constraints#

  • -2^31 <= x <= 2^31 - 1.

Approach#

Repeatedly peel off x % 10 and append to rev. Before each rev = rev * 10 + d, check whether rev would exceed bounds.

Solution#

Reverse Integer
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int d = x % 10;
x /= 10;
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && d > 7)) return 0;
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && d < -8)) return 0;
rev = rev * 10 + d;
}
return rev;
}
};

Editorial#

C++‘s % rounds toward zero, so negative inputs naturally produce negative digits, sparing us a sign branch. The overflow check must happen before the multiply: INT_MAX = 2147483647 so the last digit can be at most 7 if rev == INT_MAX / 10.

Complexity#

  • Time: O(log10 |x|).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.