It looks easy; Just add a number to the last digit. But the carry might ripple till the very beginning. 999 + 1 = 1000. So we need to keep adding 1 to the current digit till carry becomes 0. Or at the end of iteration, we add 1 to the beginning.
vector<int> plusOne(vector<int>& digits) {
int carry = 1;
int curLoc = digits.size() - 1;
while (carry and curLoc >= 0){
int curVal = digits[curLoc] + carry;
digits[curLoc] = curVal % 10;
carry = ((curVal > 9)? 1: 0);
curLoc -= 1;
}
if (curLoc == -1 && carry == 1){
digits.insert(digits.begin(), 1);
}
return digits;
}
WE used vector.insert(vector.begin(), x) here.
The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.
vector.begin is an iterator fo random access in vector.
It will shift all things back by 1. VERY INEFFICIENT. Could have used list.