整数反转

力扣

代码

package Algorithms;

/**
 * @author : zhang
 * @version : 1.0
 * @date : Create in 2021/7/27
 * @description :
 */
public class ReverseInt {
    public static void main(String[] args) {
        int x = -123456;
        int reverse = reverse(x);
        System.out.println(reverse);
    }

    public static int reverse(int x) {
        int res = 0;
        while (x != 0) {
            //判断是否大于最大整数或小于最小整数
            if (res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10) {
                return 0;
            }
            int tem = x % 10;
            res = res * 10 + tem;
            x /= 10;
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/zh-xiaoyuan/p/15068331.html