1. Description: Given a 32-bit signed integer, reverse digits of an integer. For example, you may reverse 123 to 321, -123 to -321 or 120 to 21, and so on. Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
2.翻译:给定一个32位有符号整数,将该整数每个数位的数字倒序排列。例如将123变为321,-123变为-321,120变为21。假设我们现在的环境只能够容纳32位有符号整数的大小,并且规定当倒序的整数存在溢出问题是函数返回值是0。
3.思路:第一种办法,我们可以利用模运算获得这个整数的从低到高每一个数位上的数字并且依次存到一个int数组里,然后再遍历这个数组,输出逆序的整数值。(用到Math.pow()方法,类似数制转换,最低位乘10的零次方,第二位乘10的1次方,以此类推);下面给出的代码是另一种更为巧妙的办法,也是参考了LeetCode上其他大佬的Submission的。难点是要灵活掌握模运算和除法运算对一个整数的作用,对变化过程要做到心中有数。思路详见注释。
4.代码:
class Solution {
public int reverse(int x) {
//结果用long存储,因为逆序之后还用int的话可能溢出
long result = 0;
//取x的绝对值
int temp = Math.abs(x);
//%10取整数的最后一位
///10去掉整数的最后一位,取前面几位
while(temp > 0){
result *= 10;
result += temp % 10;
if(result > Integer.MAX_VALUE){
return 0;//如果溢出则返回0
}
temp /= 10;
}
//根据x的正负,给result加上正负号
return (int)(x>=0 ? result : -result);
}
}