整数反转

 

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

示例 1:

输入: 123
输出: 321
 示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21
注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

 1 public class T07 {
 2     public int reverse(int x) {
 3         int res = 0;
 4         int left;
 5         while (x != 0) {
 6             left = x % 10;
 7             x = x / 10;
 8             if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && left > Integer.MAX_VALUE % 10)) {
 9                 return 0;
10             }
11             if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && left < Integer.MIN_VALUE % 10)) {
12                 return 0;
13             }
14             res = res * 10 + left;
15         }
16         return res;
17 
18     }
19 }

 

posted @ 2020-03-15 21:06  海绵爱上星  阅读(159)  评论(0编辑  收藏  举报