Leetcode 0007: Reverse Integer

Title description:

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.
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

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

-2^31 <= x <= 2^31 -1

Time complexity: O(logn)
only uses int to record:

  1. Calculate each digit from right to left in turn, and then accumulate it in an integer in reverse order
  2. Before each accumulation operation, it is necessary to determine whether the accumulation will exceed the int range. When res> 0, if res * 10 + x% 10> INT_MAX, it is equivalent to res> (INT_MAX-x% 10) / 10, if it is true, it is out of range (note that x is a positive number here)
    when res <0 When res * 10 + x% 10 <INT_MIN, it is equivalent to res <(INT_MIN-x% 10) / 10, if it is true, it is out of range (note that x is a negative number here)
class Solution {
    
    
    public int reverse(int x) {
    
    
        int res = 0;
        while(x != 0){
    
    
            if(res > 0 && res > (Integer.MAX_VALUE - x % 10)/10) return 0;
            if(res < 0 && res < (Integer.MIN_VALUE - x % 10)/10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43946031/article/details/113798893