-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_0066_plusOne.cc
73 lines (67 loc) · 1.29 KB
/
Problem_0066_plusOne.cc
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
vector<int> plusOne1(vector<int> &digits)
{
vector<int> d = digits;
int n = d.size();
int num = d[n - 1] + 1;
int carry = num / 10;
d[n - 1] = num % 10;
int i = n - 2;
while (i >= 0 && carry != 0)
{
int num = d[i] + carry;
d[i] = num % 10;
carry = num / 10;
i--;
}
if (carry != 0)
{
d.insert(d.begin(), carry);
}
return d;
}
vector<int> plusOne2(vector<int> &digits)
{
int n = digits.size();
for (int i = n - 1; i >= 0; i--)
{
if (digits[i] < 9)
{
digits[i]++;
return digits;
}
digits[i] = 0;
}
vector<int> ans(n + 1);
ans[0] = 1;
return ans;
}
};
void testPlusOne()
{
Solution s;
vector<int> n1 = {1, 2, 3};
vector<int> o1 = {1, 2, 4};
vector<int> n2 = {4, 3, 2, 1};
vector<int> o2 = {4, 3, 2, 2};
vector<int> n3 = {9};
vector<int> o3 = {1, 0};
EXPECT_TRUE(o1 == s.plusOne1(n1));
EXPECT_TRUE(o2 == s.plusOne1(n2));
EXPECT_TRUE(o3 == s.plusOne1(n3));
EXPECT_TRUE(o1 == s.plusOne2(n1));
EXPECT_TRUE(o2 == s.plusOne2(n2));
EXPECT_TRUE(o3 == s.plusOne2(n3));
EXPECT_SUMMARY;
}
int main()
{
testPlusOne();
return 0;
}