`
cozilla
  • 浏览: 89198 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

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

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics