Leetcode | Plus one (array-represented number plus 1)

Source: Internet
Author: User

Given a non-negative number represented as an array of digits, plus one to the number.

The digits is stored such, the most significant digit was at the head of the list. Topic Analysis:

The number represented by the array, +1, to get the result. Same as add binary, plus a backward bit. But for the container, insert the insertion function.

Class Solution {public
:
    vector<int> plusone (vector<int> &digits) {
        int len = digits.size ( );
        vector<int> Res;
        if (len = = 0) {
            res.push_back (1);
            return res;
        }
        int carry = 1;
        for (int i = Len-1;i >= 0;i--) {
            int sum = Digits[i]+carry;  First, the sum is then judged if the Carry
            if (sum>=10)
                carry = 1;
            else
                carry = 0;
            Res.insert (Res.begin (), sum%10); Inserts the element at the specified position in the container
        }
        if (carry)
            Res.insert (Res.begin (), 1);
        return res;
    }
};

I'm a re-application. To store the new value, you can also modify it based on the original data.

Class Solution {public
:
    vector<int> plusone (vector<int> &digits) {
        int i;
        for (i = digits.size ()-1;i >= 0;--i) {
            if (digits[i]! = 9) {
                ++digits[i];
                return digits;
            }
            else {
                Digits[i] = 0;
            }
        }
        All of you are 9
        if (I < 0) {
            digits.insert (Digits.begin (), 1);
        }
        return digits;
    }
;


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.