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. Topic Analysis:
The number represented by the array, +1, to get the result. Same as add binary, plus a backward bit. But for the container, insert the insertion function.
Class Solution {public
:
vector<int> plusone (vector<int> &digits) {
int len = digits.size ( );
vector<int> Res;
if (len = = 0) {
res.push_back (1);
return res;
}
int carry = 1;
for (int i = Len-1;i >= 0;i--) {
int sum = Digits[i]+carry; First, the sum is then judged if the Carry
if (sum>=10)
carry = 1;
else
carry = 0;
Res.insert (Res.begin (), sum%10); Inserts the element at the specified position in the container
}
if (carry)
Res.insert (Res.begin (), 1);
return res;
}
};
I'm a re-application. To store the new value, you can also modify it based on the original data.
Class Solution {public
:
vector<int> plusone (vector<int> &digits) {
int i;
for (i = digits.size ()-1;i >= 0;--i) {
if (digits[i]! = 9) {
++digits[i];
return digits;
}
else {
Digits[i] = 0;
}
}
All of you are 9
if (I < 0) {
digits.insert (Digits.begin (), 1);
}
return digits;
}
;