Skip to content

Commit cbb538e

Browse files
committed
Add C++ solutions for leetcode 991.
1 parent 8f0db85 commit cbb538e

File tree

3 files changed

+114
-0
lines changed

3 files changed

+114
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int brokenCalc(int startValue, int target) {
9+
if (startValue > target) return startValue - target;
10+
11+
int count = 0;
12+
while (startValue < target)
13+
{
14+
if (target % 2 == 0)
15+
{
16+
target /= 2;
17+
count++;
18+
}
19+
else {
20+
target += 1;
21+
count++;
22+
}
23+
}
24+
while (startValue > target)
25+
{
26+
target += 1;
27+
count++;
28+
if (startValue == target) return count;
29+
}
30+
return count;
31+
}
32+
};
33+
34+
// Test
35+
int main()
36+
{
37+
Solution sol;
38+
int startValue = 3;
39+
int target = 10;
40+
auto res = sol.brokenCalc(startValue, target);
41+
cout << res << endl;
42+
43+
return 0;
44+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int brokenCalc(int startValue, int target) {
9+
if (startValue > target) return startValue - target;
10+
int count = 0;
11+
while (target > startValue)
12+
{
13+
count++;
14+
if (target % 2 == 1)
15+
target++;
16+
else target /= 2;
17+
}
18+
return count + (startValue - target); /* 一旦出现 startValue >= target 的情形, 方法1代码中的第二个while循环就不需要了 */
19+
}
20+
};
21+
22+
// Test
23+
int main()
24+
{
25+
Solution sol;
26+
int startValue = 3;
27+
int target = 10;
28+
auto res = sol.brokenCalc(startValue, target);
29+
cout << res << endl;
30+
31+
return 0;
32+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int brokenCalc(int startValue, int target) {
9+
if (startValue > target) return startValue - target;
10+
11+
int count = 0;
12+
while (startValue < target)
13+
{
14+
if (target % 2 == 0)
15+
{
16+
target /= 2;
17+
count++;
18+
}
19+
else {
20+
target += 1;
21+
count++;
22+
}
23+
}
24+
return count + (startValue - target); /* 一旦出现 startValue >= target 的情形, 方法1代码中的第二个while循环就不需要了 */
25+
}
26+
};
27+
28+
// Test
29+
int main()
30+
{
31+
Solution sol;
32+
int startValue = 3;
33+
int target = 10;
34+
auto res = sol.brokenCalc(startValue, target);
35+
cout << res << endl;
36+
37+
return 0;
38+
}

0 commit comments

Comments
 (0)