7. Integer flip

  • Topic: 7. Integer Inversion
    Turn an int value and output it. If the int overflows after the inversion, it will return 0;
    64-bit integers cannot be used;

  • Idea:
    The trouble with
    this question is how to deal with overflow; this question cannot use 64-bit integers, so long can not be used, only int can be used;

1. Check before overflow: time O(log10 x): the number of digits of loop x, space O(1)
usually converts an array into numbers, res = res * 10 + nums[ i] is traversed from high to low;
In this question, you need to invert the integer, such as 1234. Just understand 4 as the high position, you can calculate the inverted value according to the above formula. The good point is that for numbers like 123000, there is no need to consider the leading 0;

//核心:先检测再更新,就不会真的溢出int了
class Solution {
    
    
public:
    int reverse(int x) {
    
    
        int res = 0;
        while (x) {
    
    
            int tmp = x % 10;
            x /= 10;
            if (res > INT_MAX / 10 || (res == INT_MAX && tmp > 7)) return 0; //上溢出前检测
            else if (res < INT_MIN / 10 || (res == INT_MIN && tmp )) return 0;//下溢出前检测
            res = res * 10 + tmp;
        }

        return res;
    }
};

2. Stupid way: use the array to flip: time O(log10 n):, O(log10 n): an extra array of digits length x

class Solution {
    
    
public:
    int reverse(int x) {
    
    
        long xx = x;
        bool isnegative = false;
        if (xx < 0) isnegative = true, xx = -xx;//防止x取INT_MIN时,取相反数溢出

        vector<int> res;
        while (xx) res.push_back(xx % 10), xx /= 10;

        long ans = 0, i = 0;
        while (i < res.size() && res[i] == 0) ++i;//跳过前导0
        for (; i < res.size(); ++i) ans = ans * 10 + res[i]; 

        if (ans > INT_MAX) return 0;//先按整数算,最后考虑符号
        else return isnegative ? -ans : ans;
    }
};

3. Great, use forced type conversion: time O(log10 n), space O(1)

class Solution {
    
    
public:
    int reverse(int x) {
    
    
        long ans = 0;  //注意是long类型
        while (x! = 0){
    
    
            ans = ans * 10 + x % 10;
            x = x / 10;
        }
        return (int)ans == ans ? (int)ans : 0;//小端序,比较低32位,若相同说明没溢出
    }
};
  • Summary:
    Method 1 needs to be mastered, method 3 is cattle B

Guess you like

Origin blog.csdn.net/jiuri1005/article/details/114994011