Given a number represented as an array of digits, plus one to the number.
看题意,意思为:
给定一个以数字数组表示的数字,再加一。
这道题目具体的意思为:
比如给定一个digits数组{1,2,3,4},那就组成了一个数字1234,把这个数+1=1235,用数组返回1235的结果。
我们需要着重考虑的是如果结果位数变多,那么数组就会溢出。我们要处理好进位的问题。
代码如下:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int size=digits.size();
int i=0;
for(i=size-1;i>=0;--i)
{
if(digits[i]!=9)
{
digits[i]++;
return digits;
}
else
{
digits[i]=0;
}
}
if(i<0)
{
digits.insert(digits.begin(),1);
}
return digits;
}
};