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的反向迭代器,从后面往前逐步+1,求出进位值,最后判断carry是否任然进位了如果进位了,就向vector中插入
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
add(digits,1);
return digits;
}
private:
void add(vector<int> &digits,int digit){
int carry=digit;
//使用vector的反向迭代器,rbegin()指向的是vector的最后一个元素
for (auto it=digits.rbegin();it!=digits.rend();++it){
*it+=carry;
carry=*it/10;
*it%=10;
}
if (carry>0)
{
digits.insert(digits.begin(),1);
}
}
};