首页 > 代码库 > LeetCode:Reverse Integer

LeetCode:Reverse Integer

题目描述:

Reverse digits of an integer.

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

思路:先判断给的数是正数还是负数还是零。如果是零,则直接返回。如果是正数,则通过%和/运算求得给定数字的各位,再重新组合得到要求得数字。如果为负数则先转换为正数,再按正数处理,最后返回时再乘-1。

代码:

int reverse(int x) {
    int * buffer;
    int i = 0;
    int j = 0;
    int reverseN = 0;

    buffer = (int *)malloc(sizeof(int)*20);

    if(x == 0)
        return 0;

    if(x > 0)
    {
        while(x != 0)
        {
            buffer[i] = x % 10;
            x = x / 10;
            i++;
        }
        while(j < i)
        {
            reverseN = reverseN * 10 + buffer[j];
            j++;
        }
        return reverseN;
    }

    if(x < 0)
    {
        x = x * -1;
        while(x != 0)
        {
            buffer[i] = x % 10;
            x = x / 10;
            i++;
        }
        while(j < i)
        {
            reverseN = reverseN * 10 + buffer[j];
            j++;
        }
        return reverseN * -1;
    }
}


LeetCode:Reverse Integer