Reverse Integer
The key idea
Build the reversed number one digit at a time by peeling the last digit off
x with x % 10 and pushing it with rev = rev * 10 + digit. Check for 32-bit overflow BEFORE the push so you never form the out-of-range value, and return 0 when it would overflow.Problem
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0 instead.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Constraints
- -2^31 <= x <= 2^31 - 1
Examples
Input: x = 123
Output: 321
Input: x = -123
Output: -321
Input: x = 120
Output: 21
Complexity
Time: O(log x) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Math / Number Theory problems
- Add BinaryEASY
- Factorial Trailing ZeroesMEDIUM
- Excel Sheet Column TitleEASY
- Greatest Common Divisor of StringsEASY
- Integer to RomanMEDIUM
- Multiply StringsMEDIUM
- Palindrome NumberEASY
- Plus OneEASY
- Roman to IntegerEASY