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 <= p <= 1000
0 <= q <= p
镜面反射。
有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角以外,每个角落都放有一个接受器,编号为 0,1,以及 2。
正方形房间的墙壁长度为 p,一束激光从西南角射出,首先会与东墙相遇,入射点到接收器 0 的距离为 q。
返回光线最先遇到的接收器的编号(保证光线最终会遇到一个接收器)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/mirror-reflection
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数学题,需要找规律。这里我直接引用grandyang大神的讲解。
时间O(1)
空间O(1)
Java实现
1 class Solution { 2 public int mirrorReflection(int p, int q) { 3 while (p % 2 == 0 && q % 2 == 0) { 4 p /= 2; 5 q /= 2; 6 } 7 if (p % 2 == 0) { 8 return 2; 9 } 10 if (q % 2 == 0) { 11 return 0; 12 } 13 return 1; 14 } 15 }