10k

7. Reverse Integer

Question

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 [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Algorithm

Just implement the reverse there:

Get the first digit of reversed number from module the original number by 10 and get last digit one by one;

Keep updating original number when the last digit was used; and the reverse integer was multiple by 10 to add the new number;

Trap here is

  1. Negative number handing;
  2. If Long type cannot be used to avoid the integer overflow, we need to keep a previous result to check if current number change back, will it be the last number.

Code

class Solution {
    public int reverse(int x) {
        int sign = 1;
        if (x < 0) {
            sign = -1;
            x = -x;
        }
        
        int res = 0;
        int prevRes = 0;
        while (x > 0) {
            prevRes = res;
            res = res * 10 + x % 10;
            if (prevRes != (res - x % 10) / 10) {
                return 0;
            }
            x = (x - x % 10) / 10;
        }
        return res * sign;
    }
}
Thoughts? Leave a comment