lc66-Plus One

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
vector<int> plusOne(vector<int>& digits) {
vector<int> res;
int l = digits.size()-1;
res = helper(digits, l);
return res;
}
vector<int> helper(vector<int> d, int i) {
if (d[i] < 9) {
vector<int> v(d.begin(), d.begin()+i);
v.push_back(d[i]+1);
return v;
}
else {
vector<int> v;
if(i>0) v = helper(d, i-1);
else v.push_back(1);
v.push_back(0);
return v;
}
}
};
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> res(digits);
int l = digits.size();
for (int i = l-1; i >= 0; i--) {
if (digits[i] == 9)
res[i] = 0;
else {
res[i]++;
return res;
}
}
res[0] = 1;
res.push_back(0);
return res;
}
};