7. Reverse Integer【Leetcode by java】

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解题:正数倒置的问题。我首先想到的是转化成字符串进行倒置,因为转化成字符串后,就不用考虑数字在个位,还是百位,还是其他什么位的。当然,负号肯定是要特殊对待的。返回值是int,还得再转回去。最重要的是,溢出问题要处理一下,Note中有提示。代码如下:

 1 class Solution {
 2     public int reverse(int x) {
 3         String str = String.valueOf(x);
 4         if(str == null)
 5             return 0;
 6         if(str.charAt(0) == '-')
 7             str = '-' + reverse_str(str.substring(1));
 8         else str = reverse_str(str);
 9         int res = 0;
10         try{
11             res = Integer.parseInt(str);
12             return res;
13         }catch(NumberFormatException e){
14             return 0;
15         }
16     }
17     public static String reverse_str(String str){
18         if(str == null || str.length() < 2)
19             return str;
20         return reverse_str(str.substring(1)) + str.charAt(0);
21     }
22 }

评论区找到一个很精简也很高效的算法,尤其是判断是否溢出的方法更加巧妙。代码如下:

 1 public int reverse(int x)
 2 {
 3     int result = 0;
 4 
 5     while (x != 0)
 6     {
 7         int tail = x % 10;
 8         int newResult = result * 10 + tail;
 9         if ((newResult - tail) / 10 != result)
10         { return 0; }
11         result = newResult;
12         x = x / 10;
13     }
14 
15     return result;
16 }

第8行处用一个newResult来暂存答案,第9行的时候,反解出result,看和原来的等不等,如果精度没有损失(依然相等),则说明没有溢出,反之有溢出。学习了!

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9163253.html