问题定义
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: [−2^31, 2^31-1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
给定一个int类型的数值,让我们将其各位数反转。假设改整数范围为[-2^31,2^31-1],并且当反向整数溢出时,函数返回0.
我的思路
让这个待被处理的数,在每次循环除以10,而新的反转数值等于前一次循环的反转数值乘以10再加上余数。
也就是关键处理句子在于
reverseInteger=reverseInteger*10+x%10;
代码
class Solution {
public int reverse(int x) {
int reverseInteger=0;
while(x!=0){
reverseInteger=reverseInteger*10+x%10;
x=x/10;
}
return reverseInteger;
}
}
出现的问题
就上面的代码,确实能够实现,但是当我要submit时候就老是会出错,反反复复检查了一下,觉得没什么毛病,但是对于溢出情况我没有处理。然后我就学习了一下其他人的代码。
学习其他人的代码
来自一位叫bitzhuwei的码友。
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;
看了他的代码,我觉得他的代码就多了一个判断,若再次反转时出现错误,就返回0(当然这个题目中有要求,我写代码的时候没注意到哈哈)。他的思想挺巧妙的,可是我还是有些疑问,溢出究竟是一种什么情况,所以有必要再研究一下。
一点思考
数值在计算机中的存储是二进制存储的,一个int类型32bit(4个字节),取第一位为符号位,因此大小在[-2^31,2^31-1]之间。
溢出情况就是,数值小于-2^31或者大于2^31-1时。举一个情况,当一个数值是2^31-1+1,也就是
011111111111111111111111111111111111111111111111111111+
000000000000000000000000000000000000000000000000000001=
000000000000000000000000000000000000000000000000000000(第一位是符号位)
所以溢出情况是数值变小了,自然就出错了。
因此这个数反转回去肯定也是错了的,因此觉得他的解决方式很巧妙,不然反转到一半都不知道怎么判断是否溢出,反正转出来的数也不会超出int的范围。