感想
我搜了一下,好像还没有搜到中文博客关于这一题的解题报告,我这里弥补一下空缺。
其数学表达式为:k = p / gcd(p, q)
表达式的意思,求p和q的最大公约数,然后p/最大公约数,就得到k,q也一样,如果p和q都是奇数,则会投射到1,如果只有p是奇数则会投射到0,否则会投射到2.至于数学原理,我并不理解,但是验证了一下确实是这样的,读者如果有更好的解释,可以跟我交流,时间复杂度度O(log(P)),空间复杂度O(1)。
problem
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 0th 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
Solution
class Solution {
public:
int mirrorReflection(int p, int q) {
int g=gcd(p,q);
p/=g;p%=2;
q/=g;q%=2;
if(p==1&&q==1) return 1;
return p==1 ? 0:2;
}
int gcd(int p,int q){
return q==0 ? p:gcd(q,p%q);
}
};
参考文献
[1]. 858. Mirror Reflection.https://leetcode.com/problems/mirror-reflection/solution/