Title:
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.
Tips:
This question is actually an operation that simulates the addition of the rounding we learned in primary school. Not very difficult.
Code:
The spatial complexity is an O (n) Method:
classSolution { Public: Vector<int> PlusOne (vector<int>&digits) { intSize = Digits.size ()-1; Digits[size]+=1; if(Digits[size] <Ten) { returndigits; } Vector<int>result; for(inti = size; i >0; --i) {if(Digits[i] = =Ten) {Digits[i]=0; Digits[i-1] +=1; } } if(digits[0] ==Ten) {Result.push_back (1); digits[0] =0; } for(inti =0; I <= size; ++i) {result.push_back (digits[i]); } returnresult; }};
The spatial complexity is an O (1) Method:
classSolution { Public: Vector<int> PlusOne (vector<int>&digits) { for(inti = Digits.size (); i--; Digits[i] =0) if(Digits[i]++ <9)returndigits; digits[0] =1; Digits.push_back (0); returndigits; }};
"Leetcode" 66. Plus One