Comment on page
66 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.
vector<int> plusOne(vector<int>& digits)
{
int end = digits.size() - 1;
while (end >= 0 && digits[end] == 9) {
digits[end--] = 0;
}
if (end == -1) {
digits.insert(digits.begin(), 1);
return digits;
}
digits[end]++;
return digits;
}
int main()
{
vector<int> test = { 1,2,3,4,5,6,7,8 };
print(plusOne(test));
vector<int> test2 = { 1,9,9,9 };
print(plusOne(test2));
vector<int> test3 = { 9,9,9,9 };
print(plusOne(test3));
}
Last modified 4yr ago