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.
代码比较长
1、vector中capacity()和size()返回值是不一样的,size是实际元素个数,capacity是可以容纳的最大元素个数。
2、貌似insert函数用begin作为参数重新使用begin会出现些问题,有空研究一下
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int i,len,temp,carry=0;
len=digits.size();
vector<int>::iterator end=digits.end();
vector<int>::iterator begin=digits.begin();
vector<int>::iterator itr=end;
for(i=0;i<len;i++)
{
if(itr==end)
{
if(len==1)
{
temp=*begin+1;
if(temp==10)
{
*begin=0;
digits.insert(begin,1,1);
return digits;
}
else
{
*begin=*begin+1;
return digits;
}
}
else
{
itr--;
temp=*itr+1;
if(temp==10)
{
carry=1;
*itr=0;
itr--;
}
else
{
*itr=*itr+1;
return digits;
}
}
}
else if(itr==begin)
{
temp=*itr+carry;
if(temp==10)
{
*itr=0;
digits.insert(begin,1,1);
}
else
{
*itr=*itr+carry;
}
}
else
{
temp=*itr+carry;
if(temp==10)
{
carry=1;
*itr=0;
itr--;
}
else
{
*itr=*itr+carry;
return digits;
}
}
}
return digits;
}
};