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
, and2
.
The square room has walls of lengthp
, and a laser ray from the southwest corner first meets the east wall at a distanceq
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:

Note:
1 <= p <= 1000
0 <= q <= p
解释下题目:
从左下角打一个点过去,然后通过最终反射会到达哪个角落(保证会到角落)
1. 数学方法
实际耗时:0ms
public int mirrorReflection(int p, int q) {
if (p == 0) {
return 2;
}
if (q == 0) {
return 0;
}
// 此时保证了肯定是斜着的线
while (p % 2 == 0 && q % 2 == 0) {
p = p / 2;
q = q / 2;
}
//p为奇数,q为奇数时,到达接收器1。
//p为奇数,q为偶数时,到达接收器0。
//p为偶数,q为奇数时,到达接收器2。
if (p % 2 == 1) {
if (q % 2 == 1) {
return 1;
} else {
return 0;
}
} else {
return 2;
}
}
一开始拿到这个题目以为是要计算角度然后计算小球的运动轨迹,后来仔细想了一想,如果保证是要到另外三个角落,那么必定是满足一定条件的,画个图画就可以了。
网友评论