66. 加一

image-20211021100630610

解题思路:

​ 方法1:直接从最后一位开始模拟整个加法的过程即可

​ 方法2:逆序查找第一个不为9的数加1,其余都设为0即可(感觉更简单)

以下是C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> ans=digits;
int index=ans.size()-1;
int add=1;
while(add==1 && index>=0){
ans[index]+=add;
add=ans[index]/10;
ans[index--]%=10;
}
//考虑最终有进位情况
if (add==1){
ans.insert(ans.begin(),1);
}
return ans;
}
};