Integer arithmetic seven reverse anti-code complement the original code

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 only store a 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.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/reverse-integer
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

This problem is relatively simple, the only difficulty is overflow. The title given conditions, can store 32-bit signed integer, a lot of comments with the larger value such as long hold judgment are not eligible. Some direct use of some known conditions, feeling not quite right, is not universal. Use c ++ macros INT_MAX and INT_MIN, not very good, if it is 31 or 30 to limit it, so we should own calculations. Own calculation int maximum and minimum values, please refer to the original code anti-code complement

class Solution {
public:
    int reverse(int x) {
        int ret = 0;
        int maxint = (1<<31)-1;
        int minint = 1 << 31;
        while(x != 0)
        {
            int pop = x % 10;
            x = x / 10;
            if(ret > 0 && ret > maxint / 10 || (ret == maxint / 10 && pop > maxint % 10))
            {
                return 0;
            }
            else if(ret < 0 && ret < minint / 10 || (ret == minint / 10 && pop < minint % 10))
            {
                return 0;
            }
            right = K * 10 + pop;
        }
        Return the right;
    }
};

 

Guess you like

Origin www.cnblogs.com/studywithallofyou/p/12023961.html