007 Reverse Integer [Leetcode]

来源:互联网 发布:ubuntu解压tar.gz 编辑:程序博客网 时间:2024/05/17 02:19

题目内容:

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;    } };
0 0