题目描述
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.
分析
1.题目要求反转之后的结果整数不能超过int的范围,若超范围直接输出0。用math中的pow函数在本地编译器上能通过,但在LeetCode官网上提示Math在该题目中未定义。那就简单粗暴给出int型的最大值和最小值,直接比较。
2.函数中的rs变量最开始定义成int型,在提交的时候显示执行过程中会溢出,改用long型。
源代码
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
ReverseInteger ri = new ReverseInteger();
System.out.println(ri.reverse(a));
}
int reverse(int x) {
long rs = 0;
int max = 0x7fffffff, min = 0x80000000;
// int max = (int) Math.pow(2,31) - 1, min = -1 * (int)Math.pow(2, 31);
if(x > max || x < min)
return 0;
for(int i = 0; x != 0; x = x/10) {
rs = rs*10 + x%10;
if(rs > max || rs < min)
return 0;
}
return (int)rs;
}
}
提交结果
总结
int型最大值:0x7fffffff
int型最小值:0x80000000
输入整数的范围是int型的取值范围时,尽量把运算中用到的变量定义为long型。