Reverse Integer

注意處理overflow和negative的問題。

class Solution {
public:
    int reverse(int x) {
        bool positive = (x>=0);
        x = abs(x);
        
        int result = 0;
        
        for(; x; x/=10)
        {
            result = result*10 + x%10;
        }
        if(result < 0)
            return -1;
        
        return positive?result:(0-result);
    }
};

class Solution {
public:
    int reverse(int x) 
    {
        bool negative = (x<0);
        if(x < 0) x = 0-x;
        if(x < 0) return 0;
        
        int result = 0;
        
        while(x != 0)
        {
            if(result > INT_MAX/10)
                return 0;
            if(result == INT_MAX/10 && (x%10) > (INT_MAX%10))
                return 0;
            result = result*10+(x%10);
            x /= 10;
        }
        return negative?(0-result):(result);
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章