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”操作,返回结果字符串。数字的高位在左边,低位在右边,与我们通常看到的数字顺序习惯相同。
本题比较简单,需要注意的地方就是在进行相加操作时,逢十进一。
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int size = digits.size();
int i = size - 1;
while (digits[i] == 9 && i > -1)
{
i--;
}
if (i == size - 1)
{
vector<int> r(digits.begin(), digits.end());
r[i]++;
return r;
}
vector<int> r;
if (i == -1)
{
r.push_back(1);
for (int j = 0; j != size; ++j)
r.push_back(0);
}
else{
for (int j = 0; j != i; ++j)
r.push_back(digits[j]);
r.push_back(digits[i] + 1);
for (int j = i + 1; j != size; ++j)
r.push_back(0);
}
return r;
}
};
原文地址:http://blog.csdn.net/angelazy/article/details/45117141