-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path66.plus-one.cpp
More file actions
46 lines (41 loc) · 1.11 KB
/
66.plus-one.cpp
File metadata and controls
46 lines (41 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "testharness.h"
#include <map>
#include <string>
#include <string.h>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
vector<int> result;
result.reserve(digits.size());
bool hasCarryOn = true;
for (int i = digits.size() - 1; i >= 0; i--) {
if (hasCarryOn) {
if (digits[i] == 9) {
result.push_back(0);
} else {
result.push_back(digits[i] + 1);
hasCarryOn = false;
}
} else {
result.push_back(digits[i]);
}
}
vector<int> ret;
ret.reserve(digits.size());
if (hasCarryOn) ret.push_back(1);
copy(result.rbegin(), result.rend(), back_inserter(ret));
return ret;
}
};
TEST(Solution, test) {
vector<int> rhs = {1, 0};
vector<int> result = plusOne(rhs);
for (int i = 0; i < result.size(); ++i)
cout << result[i] << " ";
cout << endl;
}