📝 Problem Details

input signed 32-bit integer x return x 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 OR rev == INT_MAX / 10 and the next digit > 7 → overflow.
      • If rev < INT_MIN / 10 OR rev == INT_MIN / 10 and the next digit < -8 → underflow.
    • Update rev = rev * 10 + digit.
    • Reduce x using integer division x /= 10.
  • 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;
    }
};