美文网首页
858 Mirror Reflection

858 Mirror Reflection

作者: 烟雨醉尘缘 | 来源:发表于2019-06-15 11:21 被阅读0次

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:

image

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;
        }
    }

  一开始拿到这个题目以为是要计算角度然后计算小球的运动轨迹,后来仔细想了一想,如果保证是要到另外三个角落,那么必定是满足一定条件的,画个图画就可以了。

时间复杂度O(log(p))
空间复杂度O(1)

相关文章

网友评论

      本文标题:858 Mirror Reflection

      本文链接:https://www.haomeiwen.com/subject/wfwvfctx.html