当前位置:网站首页>LeetCode 7. Integer inversion

LeetCode 7. Integer inversion

2022-07-04 20:56:00 _ Liu Xiaoyu

To give you one 32 Signed integer of bit x , Return to x The result of reversing the number part in .

If the integer after inversion exceeds 32 The range of signed integers of bits [−231, 231 − 1] , Just go back to 0.

Suppose the environment doesn't allow storage 64 An integer ( With or without sign ).

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

Code:

class Solution {
    
public:
    int reverse(int x) {
    
        long long re = 0;
        while(x)
        {
    
            re = re * 10 + x % 10;
            x /= 10;
        }
        if(re > INT_MAX) return 0;
        if(re < INT_MIN) return 0;
        return re;
    }
};

//  no need long long 
class Solution {
    
public:
    int reverse(int x) {
    
        int re = 0;
        while(x)
        {
    
            if(re > 0 && re > (INT_MAX - x % 10)/ 10) return 0;
            if(re < 0 && re < (INT_MIN - x % 10) / 10) return 0;
            re = re * 10 + x % 10;   ///  This line of code will overflow 
            x /= 10;
        }
        // if(re > INT_MAX) return 0;
        // if(re < INT_MIN) return 0;
        return re;
    }
};
原网站

版权声明
本文为[_ Liu Xiaoyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041913523162.html