LeetCode Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Thought analysis: This question is relatively simple, but there is a tricky place, that is, how to deal with the overflow situation.

First of all, we need to make it clear that no matter whether it is a 32-bit machine or a 64-bit machine, java defines int as 32 bits, so Integer.MAX_VAULE and Integer_MIN_VALUE are respectively 2^31-1 and -2^31, and the 32-bit takes the first bit as the sign bit. easy obtains the previous calculation result (considering the rule of carry or the sum of the proportional sequence). Therefore, there are two points to pay attention to when dealing with overflow in this question. The first is to handle Integer.MIN_VALUE separately, and do not directly take the absolute value, otherwise it will overflow directly. Should return 0; the second is to infer whether there is

res * 10 + posx % 10 > Integer.MAX_VALUE

But you can't write it like this directly, it will overflow when running the code from left to right, you can write it in another way to infer whether there is

res > (Integer.MAX_VALUE - posx % 10) / 10
The assumption is to return 0 directly. Finally when the x bit is negative. Returns the opposite of the result.


AC Code

public class Solution {
    public int reverse(int x) {
        //1259
        if(x == Integer.MIN_VALUE){
            return 0;//Integer.MIN_VALUE is -2^31, the abs of which is larger than Integer.MAX_VALUE(2^31 - 1)
        }
        int posx = Math.abs(x);
        int res = 0;
        while(posx != 0){
            int rem = posx % 10;
            //see whether res * 10 + posx % 10 > Integer.MAX_VALUE if yes, overflow
            //note that we move the item except res in the right to the left
            if(res > (Integer.MAX_VALUE - rem) / 10){
                return 0;
            }
            res = res * 10 + rem;
            posx /= 10;
        }
        return x>0?

res:-res; } }



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326827661&siteId=291194637