📝 Problem Details
- Title:
7. Reverse Integer
- Link: https://leetcode.com/problems/reverse-integer/
- Difficulty: Medium
- Tags/Categories: Bit-Manipulation
input signed 32-bit integer
x
returnx
with its digits reversed
edge case: the reversed number could exceed the constraint of a signed 32-bit integer
💡 Explanation of Solution
- Initialize a variable
rev
to 0. - While
x
is not 0:- Extract the last digit using
x % 10
. - Before updating
rev
, check for overflow:- If
rev > INT_MAX / 10
ORrev == INT_MAX / 10
and the next digit > 7 → overflow. - If
rev < INT_MIN / 10
ORrev == INT_MIN / 10
and the next digit < -8 → underflow.
- If
- Update
rev = rev * 10 + digit
. - Reduce
x
using integer divisionx /= 10
.
- Extract the last digit using
- Return
rev
.
⌛ Complexity Analysis
Time Complexity: O(log₁₀x) — The number of digits in `x` (since we process one digit at a time).
Space Complexity: O(1) — No additional space used.
💻 Implementation of Solution
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int digit = x % 10;
// Check for overflow
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && digit > 7)) return 0;
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && digit < -8)) return 0;
rev = rev * 10 + digit;
x /= 10;
}
return rev;
}
};