# 858. Mirror Reflection

There is a special square room with mirrors on each of the four walls.  Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0``1`, and `2`.

The square room has walls of length `p`, and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0`th receptor.

Return the number of the receptor that the ray meets first.  (It is guaranteed that the ray will meet a receptor eventually.)

Example 1:

``````Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
``````

Note:

1. `1 <= p <= 1000`
2. `0 <= q <= p`

• p为奇数，q为奇数时，到达接收器1。
• p为奇数，q为偶数时，到达接收器0。
• p为偶数，q为奇数时，到达接收器2。

``````class Solution {
public:
int mirrorReflection(int p, int q) {
while (p % 2 == 0 && q % 2 == 0) {
p /= 2; q /= 2;
}
if (p % 2 == 0) return 2;
if (q % 2 == 0) return 0;
return 1;
}
};
``````

``````class Solution {
public:
int mirrorReflection(int p, int q) {
while (p % 2 == 0 && q % 2 == 0) {
p /= 2; q /= 2;
}
return 1 - p % 2 + q % 2;
}
};
``````

``````class Solution {
public:
int mirrorReflection(int p, int q) {
return 1 - p / gcd(p, q) % 2 + q / gcd(p, q) % 2;
}
int gcd(int p, int q) {
return q ? gcd(q, p % q) : p;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/858

https://leetcode.com/problems/mirror-reflection/

https://leetcode.com/problems/mirror-reflection/discuss/141765/Java-short-solution-with-a-sample-drawing

https://leetcode.com/problems/mirror-reflection/discuss/141826/1-line-C%2B%2B-solution-using-gcd-only-4ms

https://leetcode.com/problems/mirror-reflection/discuss/141773/C%2B%2BJavaPython-1-line-without-using-any-package-or

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation