forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
52 lines (36 loc) · 892 Bytes
/
main.cpp
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
/// Source : https://leetcode.com/problems/broken-calculator/
/// Author : liuyubobobo
/// Time : 2019-02-09
#include <iostream>
#include <cassert>
using namespace std;
/// Greedy
/// Time Complexity: O(logY)
/// Space Complexity: O(1)
class Solution {
public:
int brokenCalc(int X, int Y) {
if(X >= Y) return X - Y;
int res = 0;
while(X != Y){
if(Y % 2) res ++, Y ++;
else res ++, Y /= 2;
if(X > Y)
return res + X - Y;
}
return res;
}
};
int main() {
cout << Solution().brokenCalc(2, 3) << endl;
// 2
cout << Solution().brokenCalc(5, 8) << endl;
// 2
cout << Solution().brokenCalc(3, 10) << endl;
// 3
cout << Solution().brokenCalc(1024, 1) << endl;
// 1023
cout << Solution().brokenCalc(1, 1000000000) << endl;
// 39
return 0;
}