Leetcode [array]: plus one

Source: Internet
Author: User

Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.

At first, I misunderstood the meaning of the question and thought it was to create a vector to return, so I had the following solution:

C++ code    vector<int> plusOne(vector<int> &digits) {        vector<int> result;        int carry = 1;        for (int i = digits.size() - 1; i >= 0; --i){            result.insert(result.begin(), (digits[i] + carry) % 10);            carry = (digits[i] + carry == 10);        }        if (carry)            result.insert(result.begin(), 1);        return result;    }

Later, I saw that the practices of others in discuss were all done on the original array, and I reviewed the question again. I found that the "the number" in the question should be in the original array. In this way, there is another difference: when there is no carry, the loop can be exited. The solution is as follows:

C++ code    vector<int> plusOne(vector<int> &digits) {        int carry = 1;        for (int i = digits.size() - 1; i >= 0; --i){            if (carry)            {                digits[i] += carry;                carry = (digits[i] == 10);                digits[i] %= 10;            }            else                break;        }        if (carry)        {            digits[0] = 1;            digits.push_back(0);        }        return digits;    }

Leetcode [array]: plus one

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.