Painting solution algorithm: 7 integer reversal

Topic Link

leetcode-cn.com/problems/re…

Title Description

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

Example 1:

输入: 123
输出: 321
复制代码

Example 2:

输入: -123
输出: -321
复制代码

Example 3:

输入: 120
输出: 21
复制代码

note:

Suppose we have an environment only stores the 32bit signed integer, the range of its value [−231, 231 − 1]. Please According to this hypothesis, if integer overflow after reverse it returns 0.

Problem-solving program

Thinking

  • Tags: Mathematics
  • If you do not consider this question overflow problem is very simple. There are two ideas to solve the overflow problem, the first idea is to convert a string by Jia try catchto address the way, the second idea is to solve mathematical calculations.
  • Due to the lower string conversion efficiency and use more library function, so the program does not consider the problem-solving method, but to solve mathematical calculations.
  • By circulating the numbers xof every one apart, in calculating the new value every step of determining whether or not overflow.
  • There are two overflow condition, a maximum value is an integer MAX_VALUE, and the other is an integer less than the minimum MIN_VALUE, the current calculation result is provided ans, next to pop.
  • From ans * 10 + pop > MAX_VALUEthis point of view overflow condition
    • When there is ans > MAX_VALUE / 10, and 还有pop需要添加when, it must overflow
    • When there is ans == MAX_VALUE / 10, and pop > 7when, it must overflow, 7is 2^31 - 1in single digits
  • From ans * 10 + pop < MIN_VALUEthis point of view overflow condition
    • When there is ans < MIN_VALUE / 10, and 还有pop需要添加when, it must overflow
    • When there is ans == MAX_VALUE / 10, and pop < -8when, it must overflow, 8is -2^31in single digits

Code

class Solution {
    public int reverse(int x) {
        int ans = 0;
        while (x != 0) {
            int pop = x % 10;
            if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7)) 
                return 0;
            if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8)) 
                return 0;
            ans = ans * 10 + pop;
            x /= 10;
        }
        return ans;
    }
}
复制代码

Painting Solutions

Background reply " algorithm " algorithm to join the group every day feel algorithm Watch the soul, please click on looking and forward

Reproduced in: https: //juejin.im/post/5d022cc05188255a57151f05

Guess you like

Origin blog.csdn.net/weixin_34378969/article/details/93169958