Leetcode: 7. Reverse Integer

Description

Reverse digits of an integer.

Example

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

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Subscribe to see which companies asked this question.

思路

  • 这个题好像也没有什么简便方法,注意边界条件吧

代码

  • 时间复杂度:O(m) m为输入数的有多少位
class Solution {
public:
    const int max_int = 2147483647;
    const int min_int = -2147483648;
    
    int reverse(int x) {
        if(x >= -9 && x <= 9) return x;
        if(x == min_int || x == max_int) return 0;
        
        vector<int> num(10, 0);
        bool isNeg = false;
        long long sum = 0;
        int count = 0;
        
        if(x < 0){
            x = -x;
            isNeg = true;
        }
        
        while(x){
            num[count++] = x % 10;
            x /= 10;
        }
        
        for(int i = 0; i < count; i++)
            sum = sum * 10 + num[i];
            
        if(sum > max_int){
            if(isNeg && -sum == min_int) return min_int;
            return 0;
        }
        
        return isNeg ? -sum : sum;
    }
};
posted @ 2017-05-04 21:38  JeffLai  阅读(286)  评论(6编辑  收藏  举报