力扣:有符号整数的反转问题

问题:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
代码:

 public int reverse(int x) {
       int ans = 0; // 用于放置反转后的数
       while( x != 0) {
           int a = x % 10;
           if(ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE && ans > 7)) {
           return 0;
       } //  防止循环溢出,返回0
       if(ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE && ans < -8)) {
           return 0;
       }
       ans = ans * 10 + a;
       x /= 10;
       }
       return ans;
    }

猜你喜欢

转载自www.cnblogs.com/njuptzheng/p/12788708.html