Leetcode 7: Reverse integer

Topic: Reverse integer

Given a 32-bit signed integer, the integer number is reversed.
For example, turned upside 321-123 123 -321 turned upside
assume that our environment can store 32-bit signed integer, which is the numerical range [-231 231--1]. Under this assumption, if the inversion integer overflow, 0 is returned.

Thinking

To take more than 10 Solving

  public int resverse(Integer x){
        long result = 0;
        while (x != 0) {
            result = result * 10 + x % 10;
            x /= 10;
        }
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
            result = 0;
        }
        return (int) result;
    }

Note: result here is used to store the result of inversion, the use of long type. (If int, when x is too large, there will be an overflow result after inversion, for example, x = 1534236469,

After the reverse result should be 9,646,324,351, but Integer.MAX_VALUE = 2147483647, resulting in an overflow, the final result = 1056389759, it's not the result we want
when it is used here long, judge overflow, returns result = 0

Published 80 original articles · won praise 140 · views 640 000 +

Guess you like

Origin blog.csdn.net/linjpg/article/details/104593473