[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; }};