7. 整数反转

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

示例 1:

输入: 123
输出: 321
 1 public class ReverseInteger {
 2     //方法一:转换为字符串,注意字符转换为对应的Ascll码值,以及溢出检测
 3     public static int reverse1(int x) {
 4         String s = String.valueOf(x>0 ? x : -x);
 5         int len = s.length();
 6         int result = 0;
 7         int num = 1;
 8         for(int j=0; j<len; j++) {
 9             int temp = Integer.valueOf(s.charAt(j)) - 48;
10             if(j==9 && temp>2 ){  //如果在10亿位超过2,则一定溢出,最大int数2147483647,最小-2147483648
11                 return 0;
12             }
13             if((Integer.MAX_VALUE - temp*num) > result) { //如果最大值和相加值的差大于当前数,则也会发生溢出
14                 result += temp*num;    //最大最小值的最后一位为7和8,所以不会输入一个能反转为最大最小的整数,此处大于小于均可
15             }else {
16                 return 0;
17             }
18             num = num * 10;            
19         }            
20         if(x < 0) {
21             return -result;
22         }
23         return result;
24     }
25     
26     //方法二:使用栈的形式,获取整数的最后一位数,然后弹出(删除)最后一位数
27     public static int reverse2(int x) {
28         int result = 0;
29         while(x != 0) {
30             int lastNum = x % 10;  //每次得到当前数的最后一个数字
31             x /= 10;               //删除当前数的最后一个数字
32 /*            if(result > Integer.MAX_VALUE/10 || result == Integer.MAX_VALUE/10 && lastNum > 7) {//最大2147483647
33                 return 0;
34             }
35             if(result < Integer.MIN_VALUE/10 || result == Integer.MAX_VALUE/10 && lastNum < -8) {//最小-2147483648
36                 return 0;
37             }*/
38             if(result > Integer.MAX_VALUE/10) {//这两句也是可以的,最后一个数字,也就是输入整数最高位,如果是十位数,则最高位不可能大于2
39                 return 0;
40             }
41             if(result < Integer.MIN_VALUE/10) {//对于负数来说,如果是十位数,则最高位不可能小于-2
42                 return 0;
43             }
44             result = result * 10 + lastNum;
45         }
46         return result;
47     }
48     
49     //方法三:使用Java的异常捕获机制
50     public static int reverse3(int x) {
51         boolean flag = x < 0 ? true : false;
52         if(flag) {
53             x = -x;
54         }
55         int result = 0;
56         StringBuilder sb = new StringBuilder(Integer.toString(x));
57         String reverse = sb.reverse().toString();
58         System.out.println(reverse);
59         try {
60             result = Integer.parseInt(reverse);
61             if(flag) {
62                 result = - result;
63             }
64         }catch (Exception e){
65             return 0;
66         }
67         return result;
68     }
69     
70     public static void main(String[] args) {
71         System.out.println(reverse3(156566));
72     }
73 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧
原文地址:https://www.cnblogs.com/xiyangchen/p/10908468.html