Share my solution


  • 0
    F

    My C++ Code is:

    it takes 4ms for executing.
    and the Solution is based on a factor that: the carry bit is 1 and for the number 9 + 1, so there is no need to using % or /.

    the time complex is O(n),
    but I think the XOR solution did the better job, more clean code. less compile time.

    vector<int> plusOne(vector<int> &digits) {
        int remained = 1;
        
        for (int i = digits.size() - 1; i >= 0; --i) {
            
            digits[i] += remained;
            
            if (digits[i] > 9) {
                remained = 1;
                digits[i] = 0;
            } else {
                remained = 0;
            }
        }
        
        if (remained == 1) {
            digits.push_back(0);
            digits[0] = 1;
        }
        
        return digits;
    }

Log in to reply
 

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