描述
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.
难度
Easy
题目链接:
https://leetcode.com/problems/reverse-integer/
思路
思路就是对 x 进行取余和除以 10,得到各个位数之后再拼回去,
Below is the first solutions,
public static void main(String ...args) {
System.out.println(-11 % 10);
System.out.println(123 + " : " + reverse(123));
System.out.println(-123 + " : " + reverse(-123));
System.out.println(Integer.MAX_VALUE + " : " + reverse(Integer.MAX_VALUE));
System.out.println(Integer.MAX_VALUE / 10 + " : " + reverse(Integer.MAX_VALUE / 10));
System.out.println(Integer.MIN_VALUE + " : " + reverse(Integer.MIN_VALUE));
System.out.println(Integer.MIN_VALUE / 10 + " : " + reverse(Integer.MIN_VALUE / 10));
}
public static int reverse(int x) {
int ret = 0, overMax = Integer.MAX_VALUE / 10, overMin = Integer.MIN_VALUE / 10;
for (; x!=0; x/=10) {
int p = x % 10;
if (ret > overMax || ret < overMin) {
return 0;
}
ret = ret * 10 + p;
}
return ret;
}
The solution above can solve the problem, but the code was not clear enough. Here is a better solution which seems better and clear,
One better solution
class Solution {
public int reverse(int x) {
long res = 0;
for (; x != 0; x /= 10)
res = res * 10 + x % 10;
return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res;
}
}
如上所示,这里使用了 long 类型来存储反向拼接之后的结果。而在我的解决方案中,当时考虑到 int 类型的溢出的问题,所以每次进行判断的时候使用了整型的最大值和最小值的十分之一进行判断。其实这是没有必要的。
所以,解决算法问题的时候,当程序中要求输入或者输出的类型是 int 类型,而我们直接使用 int 类型参与运算可能导致溢出的时候,可以考虑先使用 long 类型参与运算,最终返回的时候再将结果转换成 int 类型。