问题描述:
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.
思路:
一开始没读懂题目o(╯□╰)o。试了一次题目的测试后才知道,一个个 digit 放进数组里,组成一个非负整数,然后加 1 求结果。
看懂题目后就很容易了,基本难点就是操作进位,特别是在最高位需要插入时,可能会造成一些 iterator 的 incompatible
错误或是 not decrementable
的错误,前者可能是因为 vector 容器内存重新分配造成的,经过一些插入或删除的操作后再使用之前在用的迭代器,很可能出错;后者可能是因为已经来到容器头部或尾部而继续往下操作出现错误。
代码:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int>::reverse_iterator rit = digits.rbegin();
*rit += 1;
for (; rit != digits.rend(); rit++)
{
if (*rit > 9)
{
int temp = *rit;
*rit = temp % 10;
if (rit + 1 != digits.rend())
{
*(rit + 1) += 1;
}
else
{
digits.insert(digits.begin(), 1);
break;
}
}
}
return digits;
}
};