当前位置:网站首页>Leetcode notes No.7

Leetcode notes No.7

2022-07-08 01:13:00 __ Small crisp__

7. Integer inversion

Give a 32 Signed integer of bit , You need to reverse the number on each of the integers .

Be careful

Suppose our environment can only store 32 Signed integer of bit , The value range is [−231, 231 − 1]. Please follow this assumption , If the integer overflows after inversion, return 0.

Ideas

  • Through strings , However, a large number of library functions are required
  • Mathematical methods
    • By looping numbers x Every one of them took apart , When calculating a new value, each step determines whether it overflows .
    • There are two overflow conditions , One is greater than the integer maximum INT_MAX, The other is less than the integer minimum INT_MIN, Let the current calculation result be result, The next one is temp.
    • from result* 10 + temp> INT_MAX In terms of this overflow condition
      • When there is a result > INT_MAX / 10 And also temp Need to add when , It must overflow
      • When there is a result == INT_MAX / 10 And temp> 7 when , It must overflow ,7 yes 2^31 - 1 The number of digits
    • from result* 10 + temp < INT_MIN In terms of this overflow condition
      • When there is a result < INT_MIN/ 10 And also temp Need to add when , It must overflow
      • When there is a result == INT_MIN/ 10 And temp< -8 when , It must overflow ,8 yes -2^31 The number of digits

Code

int reverse(int x){
    
    int temp   = 0;
    int result = 0;

    while(x != 0) {
    
        temp = x % 10;
        if (result > INT_MAX / 10 || ((result == INT_MAX / 10) && temp > 7)) {
    
            return 0;
        }
        if (result < INT_MIN / 10 || ((result == INT_MIN / 10) && temp < -8)) {
    
            return 0;
        }
        result = 10 * result + temp;
        x /= 10;
    }
    return result;
}
原网站

版权声明
本文为[__ Small crisp__]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130546543640.html