本题难度为simple,应该是算法上比较简单(我用的String来reverse),但是细节太多了,主要说说我遇到的错误:
- ”-“的处理,负号不能reverse
- 0的处理,0在翻转的时候可能出现在第一位需要舍弃,但是只有0的时候又不能舍弃。
- 再者是长度,正负数不能超过最大值,如果用string则至少是正数不超过10位,负数不超过11位。
答案:短短几行,就可以解决上述所有问题,精彩。
难理解处:为什么要判断(int)res==res??如何控制超出整数范围的数返回0的?
public int reverse(int x) {
long res = 0;
while (x != 0) {
res *= 10;
res += x % 10;
x /= 10;
}
return (int)res == res ? (int)res : 0;
}
解释如下:
Hi, everyone!
Nice solution, but, as many others, I didn't get the line
if ((newResult - tail) / 10 != result)
.We're interested on what happens when an integer overflows. Well, it is rolled over. Practically speaking, if you would try
public static void main(String[] args) { int rollMeOver= Integer.MAX_VALUE + 1; System.out.println(rollMeOver); }
You will get as an output
-2147483648
which represents the lowest value for an integer (Integer.MIN_VALUE
).Thus, in our problem, if
newResult
is going to overflow we are sure thatnewResult / 10 != result
(this is the reason that @Inception_wzd said that we don't need to subtract the tail first because by/ 10
we are already losing the last digit).By the way, the same thing happens for the underflow.
public static void main(String[] args) { int rollMeOver= Integer.MIN_VALUE - 1; System.out.println(rollMeOver); }
This is going to output the
Integer.MAX_VALUE
which is2147483647
.Hope it helps!
Good luck! :D