您的位置:首页 > 编程语言 > C语言/C++

[leetcode]-7. Reverse Integer(C语言)

2018-03-19 16:37 381 查看
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:Input: 123
Output: 321
Example 2:Input: -123
Output: -321
Example 3:Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
主要注意的是溢出问题:如果溢出,则系统只取低32位,会造成结果错误。
int reverse(int x) {
int result,sum=0;
int b;
while(x)
{
b=x%10;
result=sum*10+b;
x=x/10;
if((result-b)/10!=sum) //判断是否溢出
return 0;
sum=result;

}
if(sum>2147483648)
return 0;
return sum;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: