Solution in C++


  • 0
    L

    typedef vector<int>::iterator VecIterator;

    class Solution {
    public:
    int reverse(int x) {
    bool isNegative = x < 0;
    long reverseX = 0;
    long maxNum = 0;

        if (isNegative) {
            x      = -x;
            maxNum = -(long)numeric_limits<int>::min(); 
        }
        else {
            maxNum = (long)numeric_limits<int>::max(); 
        }
        
        long digits = 1;
        vector<int> digitCollection;
        
        while(x >= digits) {
            digitCollection.push_back(((x % (digits * 10)) - (x % digits)) / digits );
            digits *= 10;
        }
        
        for(VecIterator iter = digitCollection.begin(); iter != digitCollection.end(); iter++) {
            digits /= 10;
            reverseX += *iter * digits;
            if (reverseX > maxNum) {
                return 0;
            }
        }
        
        return (int)(isNegative? -reverseX : reverseX);
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.