LeetCode 7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

 

1,烂解

int reverse(int x) {
    int sign = 1;
    if(x == 0x80000000)
    {
        return 0;
    }
    if(x < 0)
    {
        x = x * (-1);
        sign = -1;
    }

    double num = 0;
    while(1)
    {
        if(num * 10 > 2147483647)
        {
            return 0;
        }
        if((x - x % 10) == 0)
        {
            num = num * 10 + x % 10; 
            break;
        }else
        {
            num = num * 10 + x % 10; 
            x = x / 10;
        }
    }
    if(sign < 0)
    {
       num = num * (-1); 
    }
    return num;
}

 

posted on 2018-03-09 21:14  米兰达莫西  阅读(115)  评论(0)    收藏  举报