858. Mirror Reflection

858. Mirror Reflection

Question

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<sup>th</sup> receptor.

Given the two integers p and q, return the number of the receptor that the ray meets first.

The test cases are guaranteed so that the ray will meet a receptor eventually.

Solution

激光在箱子里折射,可以想象成在无限延展的空间内直线发射光线。
因此三个接收器可以被视作组成了一个无限延展的矩阵。

只需要将q和p化简,然后确定坐标(q, p)所对应的接收器即可。
由于接收器是间隔的,因此只需要先化简q,p后计算两者的奇偶性即可。

如果q与p皆为奇数,则返回1号接收器。
如果q是奇数,p不是,则返回0号接收器。
如果p是奇数,q不是,则返回2号接收器。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int mirrorReflection(int p, int q) {
int gcd = gcd(p, q);
p/=gcd;
q/=gcd;
boolean xIsOdd = (p & 1) == 1, yIsOdd = (q & 1) == 1;
if(xIsOdd && yIsOdd) return 1;
else if(xIsOdd) return 0;
else return 2;
}

private int gcd(int a, int b){
if(a == b) return a;
if(a > b) return gcd(b, a-b);
else return gcd(a, b-a);
}
}
Author

Xander

Posted on

2022-08-04

Updated on

2022-08-04

Licensed under

Comments