LC66 add one

It looks easy; Just add a number to the last digit. But the carry might ripple till the very beginning. 999 + 1 = 1000. So we need to keep adding 1 to the current digit till carry becomes 0. Or at the end of iteration, we add 1 to the beginning.

    vector<int> plusOne(vector<int>& digits) {
        int carry = 1;
        int curLoc = digits.size() - 1;
        while (carry and curLoc >= 0){
            int curVal = digits[curLoc] + carry;
            digits[curLoc] = curVal % 10;
            carry = ((curVal > 9)? 1: 0);
            curLoc -= 1;
        }

        if (curLoc == -1 && carry == 1){
            digits.insert(digits.begin(), 1);
        }
        return digits;
    }

WE used vector.insert(vector.begin(), x) here.
The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.
vector.begin is an iterator fo random access in vector.
It will shift all things back by 1. VERY INEFFICIENT. Could have used list.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax