The idea is just to perform the addition from right to left as usual :-)
Note that the result may be longer than the original digits
by 1
number (the carry).
1 class Solution { 2 public: 3 vector<int> plusOne(vector<int> &digits) { 4 int c = 1, n = digits.size(); 5 vector<int> sum(n, 0); 6 for(int i = n - 1; i >= 0; i--) { 7 int val = digits[i] + c; 8 sum[i] = val % 10; 9 c = val / 10; 10 } 11 if(c) sum.insert(sum.begin(), c); 12 return sum; 13 } 14 };