原题链接: https://leetcode.com/problems/reverse-integer/
1. 题目介绍
Given a 32-bit signed integer, reverse digits of an integer.
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.
给出一个32位的整数,将这个整数反转。如果反转之后的数超过了 int 类型数的范围 [−231, 231 − 1] 时,返回 0 。
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
2. 解题思路
2.1 方法1 使用长整型
拿到这个题的第一感觉是它和字符串并没有什么关系,尽管这个题被贴上了字符串的标签。对 x 逐个位取余,然后可以使用 long 类型保存反转之后的数。
long 是长整型,一共有64位,而 int 则是整型,只有32位。
如果这个long类型的数超过了 int 的范围,就返回 0,否则将其强制转换为int后返回。
但是这个方法就有一个弊端,万一题目改成输入64位的整数进行反转,那该怎么判断反转之后的数有没有超过long类型数的范围呢?因此这个方法不是万能的。
实现代码
class Solution {
public int reverse(int x) {
long ans = 0;
while(x != 0) {
ans = ans*10 + x % 10;
x /= 10;
}
if(ans > Integer.MAX_VALUE || ans<Integer.MIN_VALUE ) {
return 0;
}
else {
return (int)ans;
}
}
}
2.2 方法2 判断溢出
注:以下思路来自 https://www.cnblogs.com/wmx24/p/9149916.html
在方法1中,ans 是 long 类型,在方法2中我们仍然使用 int 类型。如何判断 ans 是否溢出呢?
ans = temp*10 + x % 10
比较 ans/10 的值与 temp 是否相等可以判断ans是否溢出。如果整数不溢出显然相等,否则说明反转后的整数溢出,直接返回0。
class Solution {
public int reverse(int x) {
int ans = 0;
while(x != 0) {
int temp = ans;
ans = temp*10 + x % 10;
if(ans/10 != temp) {
return 0;
}
x /= 10;
}
return ans;
}
}