[leetcode]66. Plus One
Analysis
paper终于提交啦,但是过的可能性很小的感觉 —— [ 坚持坚持啊 ]
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
题目意思很简单,就是一个数用数组来表示,然后加一,最后把结果用数组输出就可以了,看他给的样例基本就能明白。所以要注意进位就可以了,同时要对超过10的那个数字取余。
提交时的一个没过的样例:
input [9]
output [1,0] (如果不注意可能就会输出[1, 10]).
Implement
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> res;
int len = digits.size();
if(len==1 && digits[0]==0){
res.push_back(1);
return res;
}
digits[len-1] += 1;
for(int i=len-1; i>=0; i--){
res.push_back(digits[i]);
cout<<res[i]<<endl;
}
for(int i=0; i<len; i++){
if(res[i]>=10){
res[i]=res[i]-10;
cout<<res[i]<<endl;
if(i==len-1){
res.push_back(1);
}
else
res[i+1]+=1;
}
}
vector<int> res1;
for(int i=res.size()-1; i>=0; i--)
res1.push_back(res[i]);
return res1;
}
};