[Leetcode] Reverse Integer

Reverse IntegerDec 26 '116571 / 11753

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

» Solve this problem (link t

尽是做点简单来安慰自己。

#include <stdlib.h>     /* atoi */
#include <stdio.h>

class Solution {
public:
    int countDigit(int n) {
        int c = 0;
        if (n < 0) n=-n;
        while (n > 0) {
            c++;
            n /= 10;
        }
        if (c==0) c = 1;
        return c;
    }
    void itoa(int n, char*a) {
        int len = countDigit(n);
        a[len] = '\0';
        int i = len-1;
        while (n > 0) {
            a[i--] = '0' + n % 10;
            n /= 10;
        }
    } 
    
    int reverse(int x) {
        bool neg = false;
        if (x < 0) {
            neg = true;
            x = -x;
        }
        char a[33], b[33];
        memset(a, 0, 33);
        memset(b, 0, 33);
        itoa(x, a);
        int len = strlen(a);
        char *s = a, *e = a + len - 1;
        while (s < e && *e == '0') e--;
        char *bb = b;
        while (e >= s ) *(bb++) = *(e--); 
        *bb = '\0';
        int y = atoi(b);
        if (neg) return -y;
        else return y;
    }
};

猜你喜欢

转载自cozilla.iteye.com/blog/1921754