Reverse Integer

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 7

int 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值