[Leetcode] Plus One

Source: Internet
Author: User

Plus One

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.

Problem Solving Ideas:
The problem is quite simple, but I did not understand the first test instructions (my English is not good), this problem is intended to use an array to represent a nonnegative integer, such as: [1,0,9] represents 109. Add 1 to this array. Understanding this, it is much easier. Here's the code:

Class Solution {public:    vector<int> plusone (vector<int> &digits) {        int len = Digits.size ();        vector<int> result;        int over = 1;        for (int i=len-1, i>=0; i--) {            int number = Digits[i] + over;            over = NUMBER/10;            Result.insert (Result.begin (), number%);        }        if (over>0) {            Result.insert (Result.begin (), over);        }                return result;}    ;
Notice the use of the Insert method of the vector. The underlying implementation of the vector is an array, and each time an element is added to the first position, it is equivalent to moving him back one at a time, which is time-consuming. Consider using the stack to save the results, and finally the stack. Here's the code:
Class Solution {public:    vector<int> plusone (vector<int> &digits) {        int len = Digits.size ();        int* stack = new int[len+1];        int top = 0;        int over = 1;        for (int i=len-1;i>=0; i--) {            int number = Digits[i] + over;            over = NUMBER/10;            stack[top++] = number%10;        }        if (over>0) {            stack[top++] = over;        }        vector<int> result;        while (top>0) {            result.push_back (stack[--top]);        }        Delete stack;        return result;}    ;


[Leetcode] 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.