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