|
| 1 | +Mirror Reflection |
| 2 | + |
| 3 | +Medium |
| 4 | + |
| 5 | +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. |
| 6 | +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. |
| 7 | +Given the two integers p and q, return the number of the receptor that the ray meets first. |
| 8 | +The test cases are guaranteed so that the ray will meet a receptor eventually. |
| 9 | + |
| 10 | +Example 1: |
| 11 | + |
| 12 | +Input: p = 2, q = 1 |
| 13 | +Output: 2 |
| 14 | +Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. |
| 15 | +Example 2: |
| 16 | +Input: p = 3, q = 1 |
| 17 | +Output: 1 |
| 18 | + |
| 19 | +Constraints: |
| 20 | +1 <= q <= p <= 1000 |
| 21 | +Time Complexity-o(logn) |
| 22 | +Space Complexity-o(1) |
| 23 | + |
| 24 | +Java Solution |
| 25 | + |
| 26 | +class Solution { |
| 27 | + public int mirrorReflection(int p, int q) { |
| 28 | + |
| 29 | + while (q % 2 == 0 && p % 2 == 0) { |
| 30 | + p=p/2; |
| 31 | + q=q/2; |
| 32 | + } |
| 33 | + if (q % 2 == 0) { |
| 34 | + return 0; |
| 35 | + |
| 36 | + } else if (p % 2 == 0) { |
| 37 | + return 2; |
| 38 | + } else { |
| 39 | + return 1; |
| 40 | + } |
| 41 | + |
| 42 | + } |
| 43 | +} |