LetCode-Algorithm-Integer Inversion

Title.png

First of all, the problem is that if you want to reverse the integer 123, you need to flip it to 321, and 23 is 32.
We first found the law
321 = 3X10 2 + 2X10 1 + 3X10 0

123 reversed to 321 is (123% 10) X10 2 + (12% 10) X10 2 + (1% 10) X10 2

After drawing the law, we can write the method through this law
as follows:

public class Solution {
    public int Reverse(int x) {
    int num = 0;
    while(x != 0){        
        num = num * 10 + x % 10;
        x /= 10;
    }
    return num;
  }
}

However, it should be noted that there is a requirement to assume that our environment can only store 32-bit signed integers, and its value range is [−2 31 , 2 31 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

−231=-2147483648, 231 − 1=2147483647

We got it after modification

public class Solution {
    public int Reverse(int x) {
    long num = 0;
    
    while(x != 0){        
        num = num * 10 + x % 10;
        x /= 10;
    }
    if(num > 2147483647 || num < -2147483648)
        return 0;
    
    return (int)num;
}
}
Published 29 original articles · Like 11 · Visits 10,000+

Guess you like

Origin blog.csdn.net/u010840685/article/details/105297724