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.
就是将数的每一个数字保存在数组中,类似大数操作,注意使用反向迭代器。
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
vector<int>::reverse_iterator iter = digits.rbegin();
int carry = 0;
*iter += 1;
while (iter != digits.rend()) {
*iter += carry;
if (*iter > 9) {
*iter -= 10;
carry = 1;
iter++;
}
else {
carry = 0;
break;
}
}
if (iter == digits.rend() && carry == 1)
digits.insert(digits.begin(), carry);
return digits;
}
};