Reverse Integer
Reverse Integer
Math
Problem Statement
Given a signed 32-bit integer x, reverse digits of an integer. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Example
Example 1:
Input: x = 123
123321
Output: 321
Solution (Pop and Push Digits)
To reverse an integer, we can repeatedly "pop" the last digit off the number and "push" it onto the back of a new reversed number. We must also be careful about potential integer overflow.
Algorithm Steps
- Initialize a reversedvariable to 0.
- Loop while the input number xis not 0.
- In each iteration, get the last digit of x(the "pop" operation).
- Before adding the new digit to reversed, check if doing so would cause an overflow. If it would, return 0.
- "Push" the popped digit onto reversedby multiplying it by 10 and adding the digit.
- Remove the last digit from x.
- After the loop, return the reversednumber.
Remaining (x)
123
Reversed (rev)
0
Start with x = 123.
Reverse Integer Solution