AAlgoLoopSpaced repetition for LeetCode
MEDIUMMath / Number TheoryLeetCode ↗

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

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

410310
Step-by-step visualization
Start free →

More Math / Number Theory problems