[LeetCode] Plus One

Source: Internet
Author: User

[LeetCode] Plus One
 

Plus One

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.

Solution:
This question is quite simple, but I didn't understand the question at first (my English is not good). The intention of this question is to use an array to represent a non-negative integer, for example, 9]: 109. Add 1 to the array. It is much easier to understand this. The following code is used:

class Solution {public:    vector
 
   plusOne(vector
  
    &digits) {        int len = digits.size();        vector
   
     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 % 10);        }        if(over>0){            result.insert(result.begin(), over);        }                return result;    }};
   
  
 
Note the use of the insert method of vector. The underlying implementation of vector is an array. Each time an element is added to the first position, it is equivalent to moving the element one after each time, which is time-consuming. You can consider using the stack to save the result and finally output the stack. The following code is used:
class Solution {public:    vector
 
   plusOne(vector
  
    &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
   
     result;        while(top>0){            result.push_back(stack[--top]);        }        delete stack;        return result;    }};
   
  
 


Related Article

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.