贴原题:
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.Note: The input is assumed to be a 32-bit signed integer. Your
function should return 0 when the reversed integer overflows.
解析:
本题是要让翻转一个32位的整数,负数只翻转数值部分,符号位保持不变。
我感觉这道题最难的点在于如何判断一个数翻转之后是否溢出。(这一点我一会在下面做个总结)
贴代码:
int reverse(int x) {
int y=0;//需要返回的数
while(x)
{
int temp=y;//暂存y的值
y=y*10+x%10;//倒序;把x的最低位依次压入y的最低位
if((y-x%10)/10!=temp)//反向推,若推不出原值则溢出
{
return 0;
}
x/=10;
}
return y;
}
总结:
如何判断是否溢出?
其实看我上面的代码也可以看得出了,只要把这个式子反着推过来,再来看是否相等就行了。
- 加法溢出判断:若c=a+b; c-a!=b则溢出;或者a, b>0, c<0溢出;或者a, b<0, c>0溢出;
- 减法溢出判断:若c=a-b; c+b!=a则溢出;
- 除法溢出判断:若b!=0 && a/b=c; b*c!=a则溢出
乘法溢出判断:若c=a*b; a!=0 && c/a!=b则溢出
以上全为我个人总结,如有错误还请大家指出!