LeetCode: 7. integer reversal

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1 : 

Input: 123 
Output: 321 
 Example 2 : 

Input: -123 
Output: -321 
Example 3 : 

Input: 120 
Output: 21 
Note: 

Suppose we have an environment can store the 32-bit signed integer, then the value range [-2 ^ 31, 2 ^ 31 - 1] Please According to this hypothesis, if integer overflow after reverse it returns 0.

Ideas:

This question is most important is that after the reversal attention will overflow, so every time to pay attention during the reverse operation is causing overflow

//判断是否越界
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
public int reverse(int x) {
    int result = 0;
    while(x != 0) {
       int pop = x % 10;
       //判断是否越界
       if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
       if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
       result = result * 10 + pop;
       x /= 10;
    }
       return result;
}

Complexity Analysis

Time complexity: O (log (x)), x has about log10 (x) digits

Complexity Space: O (1).

Author: LeetCode
link: https: //leetcode-cn.com/problems/two-sum/solution/zheng-shu-fan-zhuan-by-leetcode/
Source: stay button (LeetCode)

Guess you like

Origin www.cnblogs.com/aoeiuvAQU/p/11362007.html