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.
给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
输入: 123 输出: 321
示例 2:
输入: -123 输出: -321
示例 3:
输入: 120 输出: 21
注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
实现代码一:思路非常常规,将x逐位取出,然后再生成其颠倒的数即可。注意判断正负和判断数值溢出即可。
class Solution {
public int reverse(int x) {
boolean neg = false;
if(x < 0 ){
neg = true;
x = -x;
}
long res = 0L;
int tmp = 0;
while(x != 0){
tmp = x%10;
x /= 10;
res = res*10 + tmp;
}
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
res = 0;
if(neg == true)
res = -res;
return (int)res;
}
}
代码实现二:
class Solution {
public int reverse(int x) {
boolean tag = false; //记录x正负
if(x == Integer.MIN_VALUE)//如果x为最小值 即-2147483648时,那么其Math.abs(x)求绝对值的结果与该值相同且为负。
return 0;
if(x < 0){ //如果x为负数的话,取其绝对值
tag = true;
x = Math.abs(x);
}
String tmp = Integer.toString(x); //将x转化为对应的字符串
String res = new StringBuilder(tmp).reverse().toString(); //将字符串翻转
long result = Long.parseLong(res); //将字符串转换为long
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) //反转后数值溢出
return 0;
if(tag == true) //还原负数
result = -result;
return (int) result;
}
}