您的位置:首页 > 其它

007 Reverse Integer [Leetcode]

2015-11-11 16:31 465 查看
题目内容:

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.

没什么难度,只要考虑周全异常情况处理即可。

代码:

class Solution {
public:
int reverse(int x) {
char num[12];
int result(0);
int length = sprintf(num, "%d", x);
bool allZero = true;
int start(0), end(length-1);

if(num[0]=='-' || num[0]=='+')
++start;

while(start < end) {
if(num[end] != '0')
allZero = false;
char temp(num[start]);
if(!allZero) {
num[start++] = num[end];
num[end--] = temp;
}
else
num[end--] = '\0';
}

sscanf(num, "%d", &result);
char cmp[12];
sprintf(cmp, "%d", result);
if(strcmp(cmp, num) == 0)
return result;
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: