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.
At first, I misunderstood the meaning of the question and thought it was to create a vector to return, so I had the following solution:
C++ code vector<int> plusOne(vector<int> &digits) { vector<int> result; int carry = 1; for (int i = digits.size() - 1; i >= 0; --i){ result.insert(result.begin(), (digits[i] + carry) % 10); carry = (digits[i] + carry == 10); } if (carry) result.insert(result.begin(), 1); return result; }
Later, I saw that the practices of others in discuss were all done on the original array, and I reviewed the question again. I found that the "the number" in the question should be in the original array. In this way, there is another difference: when there is no carry, the loop can be exited. The solution is as follows:
C++ code vector<int> plusOne(vector<int> &digits) { int carry = 1; for (int i = digits.size() - 1; i >= 0; --i){ if (carry) { digits[i] += carry; carry = (digits[i] == 10); digits[i] %= 10; } else break; } if (carry) { digits[0] = 1; digits.push_back(0); } return digits; }
Leetcode [array]: plus one