ReverseInteger

public class ReverseInteger {
    public static int reverse(int x)
    {
        long ret = 0;
        //如果是个位数,直接返回。
        if(x/10 == 0)
            return x;
        //循环的时候要循环商,因为会有例如302,20这样的含有0的情况。
        while(x!=0)//条件别携程x/10!=0;要看循环体里面最后的结果。
        {
            int mod = x%10;
            ret = ret*10 + mod;
            //要判断溢出的情况,比如输入11234556789是整数,但是反过来就溢出了。
            if(ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE)
                ret = 0;
            x = x/10;
        }
        //return new Long(ret).intValue();
        return (int)ret;
    }
    
    public static void main(String[] args)
    {
        int a = 302;
        System.out.println(reverse(a));
    }
}

此题很简单,要考虑整数溢出的情况。

原文地址:https://www.cnblogs.com/masterlibin/p/5522956.html