一.问题描述
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.
二.我的解题思路
本题比较容易,直接把结果vector初始化为digits。然后从最后一位开始计算,如果不需要进位,那么直接return。如果最高位加到最后的结果是大于10的,那么就使用vector的insert方法,在最高位前面插入一个1.测试通过的程序如下:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size();
vector<int> res(digits.begin(),digits.end());
if(len==0) return res;
int flag=1;
for(int i=len-1;i>=0;i--){
int curr = digits[i];
if(curr+flag<10){
res[i]=curr+flag;
flag=0;
return res;
}
else{
res[i]=curr+flag-10;
flag=1;
}
}
res.insert(res.begin(),1,1);
return res;
}
};
数组加一的C++实现
本文介绍了一种解决数组形式非负整数加一问题的方法。通过C++实现,从数组最后一位开始计算,遇到进位则更新相应位值。若最高位进位,则在最前面插入1。
152

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



