LeetCode simple solution - 7, integer inversion

Problem Description

Given a 32-bit signed integer x , return the result of inverting the digits in each bit of x.

Returns 0 if the inverted integer exceeds the range [−231, 231 − 1] for a 32-bit signed integer .

Assume the environment does not allow storing 64-bit integers (signed or unsigned).

Example 1

输入:x = 123 
输出:321

Example 2

输入:x = -123
输出:-321

Example 3

输入:x = 120
输出:21

Example 4

输入:x = 0
输出:0

problem solved

1. Ideas and Algorithms

This question is very simple if the overflow problem is not considered. There are two ways to solve the overflow problem,

  • The first idea is to solve it by string conversion and try catch ;
  • The second idea is to solve it through mathematical calculations .

Due to the low efficiency of string conversion and the use of more library functions, the solution does not consider this method, but solves it through mathematical calculations .

Each bit of the number x is disassembled by looping, and each step of calculating a new value is judged whether it overflows .
There are two overflow conditions,

  • One is greater than the integer maximum value MAX_VALUE ,
  • One is less than the integer minimum value MIN_VALUE ,

Let the current calculation result be ans , and the next bit be pop .

Judging from the overflow condition of ans * 10 + pop > MAX_VALUE

  • When there is ans > MAX_VALUE / 10 and there is still pop to be added, it must overflow
  • When ans == MAX_VALUE / 10 and pop > 7 , it must overflow, 7 is the single digit of 2^31 - 1

Judging from the overflow condition of ans * 10 + pop < MIN_VALUE

  • When ans < MIN_VALUE / 10 and pop needs to be added, it must overflow
  • When ans == MIN_VALUE / 10 and pop < -8 , it must overflow, 8 is the single digit of -2^31

2. 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;
    }
}

3. Graphical method

Graphical method

Guess you like

Origin blog.csdn.net/weixin_45075135/article/details/114360055