0858. Mirror Reflection (M)

Mirror Reflection (M)

题目

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

题意

四面墙装有镜子,其中三个角装有传感器,从剩余的那个角打出一束激光,要求判断第一个接收到激光的传感器。

思路

将激光按照可以穿透镜面进行处理,参考官方解答[LeetCode] 858. Mirror Reflection 镜面反射


代码实现

Java

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

    private int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
}
posted @ 2020-11-17 19:35  墨云黑  阅读(142)  评论(0编辑  收藏  举报