Reverse Integer
Reverse Integer
Math
Problem Statement
Given a signed 32-bit integer x
, reverse its digits. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0.
Examples
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Solution (Pop and Push Digits)
We can reverse the integer by repeatedly "popping" the last digit from the input number and "pushing" it to the back of the result.
The main challenge is handling potential overflow. Before we "push" a new digit, we must check if doing so would exceed the 32-bit integer limits.
Algorithm Steps
- Initialize
reversed = 0
. - While
x
is not 0: - Pop the last digit:
digit = x % 10
. - Update
x = x / 10
. - Before pushing the digit, check for overflow. If
reversed > MAX / 10
or (reversed == MAX / 10
anddigit > 7
), it will overflow. Same logic applies for the minimum value. - Push the digit:
reversed = reversed * 10 + digit
. - Return
reversed
.
Current x
123
Reversed
0
Initial state: x = 123
Reverse Integer Solution