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.)
Input: p = 2, q = 1 Output: 2 Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
1 <= p <= 1000
0 <= q <= p
# @param {Integer} p
# @param {Integer} q
# @return {Integer}
def mirror_reflection(p, q)
a, b = p, q
while b != 0
a, b = b, a % b
end
if p / a % 2 == 0
return 2
elsif q / a % 2 == 0
return 0
else
return 1
end
end
impl Solution {
pub fn mirror_reflection(p: i32, q: i32) -> i32 {
let mut a = p;
let mut b = q;
while b != 0 {
let tmp = b;
b = a % b;
a = tmp;
}
match (p / a % 2, q / a % 2) {
(0, _) => 2,
(1, 0) => 0,
(_, _) => 1,
}
}
}