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.
solution:
一个用数组表示的整数,数组的每一个元素代表这个整数的一位数字,求这个整数加1之后所代表的数组
code:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> result;
int flag = 1;
for (int i = digits.size() - 1; i >= 0; i--) {
if (digits[i] == 9 && flag == 1) {
result.push_back(0);
flag = 1;
}
if (digits[i] != 9 && flag == 1) {
flag = 0;
result.push_back(digits[i] + 1);
continue;
}
if (flag == 0) {
result.push_back(digits[i]);
}
}
if (flag == 1) {
result.push_back(1);
}
reverse(result.begin(), result.end());
return result;
}
};