您的位置:首页 > 其它

15算法课程 66. Plus One

2017-10-05 20:45 316 查看

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: