Reverse Integer

来源:互联网 发布:逆战血手队伤数据qq群 编辑:程序博客网 时间:2024/06/05 10:22

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

一开始做的时候,果然没有考虑好提示的两种情况。

第一种情况其实不影响做题,10100,翻过来也只能输出为101。

第二种情况就要好好斟酌了,如何判断是否溢出呢?显然如果求出来反转数n<0,说明n肯定溢出了。

但是,n有可能“溢出多次”,即溢出后二进制符号位仍为0,故溢出后可能仍为正。

我先想了个笨办法,那就是当求出的n>=0时,如果n与原始数x不对称时,说明n也肯定溢出了。

后来做了下一道题,看了glibc的atoi()函数,发现里面的溢出处理,才了解到了还有更好的办法。

C语言代码如下:

#define INT_MAX 2147483647#define INT_MIN -2147483648#define CUT_OFF 214748364#define CUT_LIM 7int reverse(int x){int flag = 0, n = 0, i =0;int origin, m;if(x == INT_MIN)return 0;if(x < 0){flag = 1;x = -x;}while(x != 0){if(n > CUT_OFF || (n == CUT_OFF && x % 10 > CUT_LIM))return 0;n = n * 10 + x % 10;x = x / 10;i++;}if(flag)n = -n;return n;}


0 0
原创粉丝点击