forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
57 lines (46 loc) · 1.19 KB
/
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
53
54
55
56
57
/// Source : https://leetcode.com/problems/mirror-reflection/description/
/// Author : liuyubobobo
/// Time : 2018-06-25
#include <iostream>
#include <cassert>
using namespace std;
/// Simulation
/// Time Complexity: O(p)
/// Space Complexity: O(1)
class Solution {
public:
int mirrorReflection(int p, int q) {
int d = 1;
bool left = true;
int y = 0;
while(true){
y += d * q;
left = !left;
if(y == p && left)
return 2;
else if(y == p && !left)
return 1;
else if(y == 0)
return 0;
if(y > p){
assert(d == 1);
y = p - (y - p);
d = -1;
}
else if(y < 0){
assert(d == -1);
y = -y;
d = 1;
}
}
assert(false);
return -1;
}
};
int main() {
cout << Solution().mirrorReflection(2, 1) << endl; // 2
cout << Solution().mirrorReflection(4, 3) << endl; // 2
cout << Solution().mirrorReflection(3, 2) << endl; // 0
cout << Solution().mirrorReflection(3, 1) << endl; // 1
return 0;
}