LeetCode算法入门- Reverse Integer-day6
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
class Solution {
public int reverse(int x) {
long result = 0;
//取绝对值
int temp = Math.abs(x);
while(temp > 0){
//核心是这里,取反的关键
result = result * 10 + temp % 10;
temp = temp / 10;
}
//记得判断是否溢出,这里很关键,这道题的关键
if(result > Integer.MAX_VALUE)
return 0;
if(x >= 0)
return (int)result;
//这里的符号是另外来进行判断,还有就是强制类型转换,将long强转为int
else return -(int)result;
}
}
方法二:将int类型转换为StringBuffer类型,然后调用reverse()方法
class Solution {
public int reverse(int x) {
int temp = 0;
//这里是原因在下面图片
if(x == -2147483648)
return 0;
// temp = -x;
else
temp = Math.abs(x);
String str = Integer.toString(temp);
//记得要转换为StringBuffer类型才行
StringBuffer sb = new StringBuffer(str);
String reverseStr = sb.reverse().toString();
//将字符串类型转换为长整型(以防它出界)
long l = Long.parseLong(reverseStr);
if(l > Integer.MAX_VALUE)
reverseStr = "0";
if(x > 0)
return Integer.parseInt(reverseStr);
else
return -Integer.parseInt(reverseStr);
}
}