Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
逆转一个整数。题目意思很简单,但是有许多需要注意的点。例如,溢出。
题目在Spoiler里面说了溢出应该返回0。但是不看Spoiler谁TM知道溢出要如何处理OJ才判对……LeetCode的题目有时候就得猜……
代码如下:
int reverse(int x) { int sign = x >= 0 ? 1 : -1; int res = 0, t; if (x < 0) x = -x; while (x > 0) { t = res * 10 + x % 10; if ((t - x % 10) / 10 != res) return 0; else { res = t; x /= 10; } } return res * sign; }
代码是很简单,处理溢出就是逆向做原来的运算,如果还能得到原先的数字,那么就没有溢出。当然我也遇到过明明溢出了结果还能得到原结果的例子……忘了在哪遇到的了,总之这个是很幸运的AC。
溢出,溢出,溢出,一定要记住,一定要在将来的程序里对这种边界条件敏感一些才行。