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.
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.
题目:一个整数按照每一位存在数组里面,然后返回整数 + 1之后的数组
所以:一位一位处理,不全部提出来
class Solution {
public:
vector<int> plusOne(vector<int>& dig)
{
int flag = 0;
int pos = dig.size();
while ( (--pos) >= 0 )
{
if (pos == dig.size() - 1)
{
if (dig[pos] < 9)
{
dig[pos]++;
return dig;
}
else
{
dig[pos] = 0;
flag = 1;
}
}
else
{
if (dig[pos] + flag < 10)
{
dig[pos]++;
return dig;
}
else
dig[pos] = 0;
}
}
if (flag==1)
{
dig.insert(dig.begin(), 1);
}
return dig;
}
};
本文介绍了一个整数通过数组表示,并在此基础上实现加一操作的算法。该算法逐位处理数组中的数字,处理进位情况,并在必要时在数组最前方插入1以形成新的整数。
577

被折叠的 条评论
为什么被折叠?



