Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
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> res;
vector<int> tempres;
int jinwei=0;
int n = digits.size();
int num = digits[n-1] + 1;
if (num >= 10)
{
jinwei = 1;
tempres.push_back(num-10);
for (int i = n - 2; i >= 0; i--)
{
num = jinwei + digits[i];
if (num >= 10)
{
tempres.push_back(num - 10);
jinwei = 1;
}
else
{
tempres.push_back(num);
jinwei = 0;
}
}
}
else
{
jinwei = 0;
tempres.push_back(num);
for (int i = n - 2; i >= 0; i--)
{
num = jinwei + digits[i];
if (num >= 10)
{
tempres.push_back(num - 10);
jinwei = 1;
}
else
{
tempres.push_back(num);
jinwei = 0;
}
}
}
if (jinwei == 1)
tempres.push_back(1);
for (int i = tempres.size() - 1; i >= 0; i--)
{
res.push_back(tempres[i]);
}
return res;
}
};