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.
Test instructions: Given an array that represents the number of non-negative bits, the number is now added one, and the resulting array is added.
Analysis: Because the length of the array may change after the addition, it is not straightforward to add one directly behind the array. The array can be flipped first, the bits go to the front, and then from the go to add one, and finally determine if the last one added more than ten, the array length plus one, the code is as follows:
Code (c + +):
classSolution { Public: vector<int>PlusOne ( vector<int>& digits) {intn = digits.size (); Reverse (Digits.begin (), Digits.end ());inttemp =0, flag =false; for(inti =0; I<n; i++) {if(i==0) temp =1;intsum = digits[i] + temp; Digits[i] = sum%Ten; temp = sum/Ten;if(i = = n1&& sum >=Ten) flag =true; }if(flag) {Digits.resize (n+1); Digits[n] = temp; } reverse (Digits.begin (), Digits.end ());returnDigits }};
Leetcode[66]-plus One