forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
mirror-reflection.cpp
38 lines (34 loc) · 937 Bytes
/
mirror-reflection.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
// Time: O(1)
// Space: O(1)
class Solution {
public:
int mirrorReflection(int p, int q) {
// explanation commented in the following solution
return (p & -p) > (q & -q) ? 2 : (p & -p) < (q & -q) ? 0 : 1;
}
};
// Time: O(log(max(p, q))) = O(1) due to 32-bit integer
// Space: O(1)
class Solution2 {
public:
int mirrorReflection(int p, int q) {
const auto lcm = p * q / gcd(p, q);
// let a = lcm / p, b = lcm / q
if (lcm / p % 2 == 1) {
if (lcm / q % 2 == 1) {
return 1; // a is odd, b is odd <=> (p & -p) == (q & -q)
}
return 2; // a is odd, b is even <=> (p & -p) > (q & -q)
}
return 0; // a is even, b is odd <=> (p & -p) < (q & -q)
}
private:
int gcd(int a, int b) {
while (b != 0) {
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}
};