描述
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321Example 2:
Input: -123
Output: -321Example 3:
Input: 120
Output: 21Note:
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类型取余比较麻烦,就使用字符串逆序读取。
这里使用的是手动循环逆序,在逆序的同时消除开头的0。一开始使用Integer.parseInt()将转换完的StringBuffer化为int,忽视了要求最后的如果翻转完后溢出的处理。

后来改为用long型记录数据(按进位将每个数字相加),并且和Integer.MAX_VALUE相比较,如果发生溢出就返回0.
class Solution {
public int reverse(int x) {
boolean posi = true, allZero = true;
if(x<0){
posi = false;
x = -x;
}
//字符串逆序去0处理
String temp = Integer.toString(x);
StringBuffer sb = new StringBuffer();
for(int i = temp.length()-1; i>=0; i--){
if(temp.charAt(i) != '0'){
allZero = false;
}
if(!allZero){
sb.append(temp.charAt(i));
}
}
//使用long防止溢出
temp = sb.toString();
long check = 0;
for(int i = 0;i<temp.length();i++){
check = check * 10 + temp.charAt(i) - '0';
if(check > (long)Integer.MAX_VALUE){
return 0;
}
}
//返回值
if(posi){
return (int)check;
}else{
return -(int)check;
}
}
}Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 37.2 MB, less than 5.55% of Java online submissions for Reverse Integer.
另一种思路
评论区见到的,使用除法和求余。并判断两个数字的关系来确定是否发生了溢出。
Only 15 lines.
If overflow exists, the new result will not equal previous one.
No flags needed. No hard code like 0xf7777777 needed.
class Solution {
public int reverse(int x){
int result = 0;
while (x != 0){
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}
}Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 37 MB, less than 5.55% of Java online submissions for Reverse Integer.
时间和空间消耗相差不多。