[leetcode] 858. Mirror Reflection

441 篇文章 0 订阅
284 篇文章 0 订阅

感想

我搜了一下,好像还没有搜到中文博客关于这一题的解题报告,我这里弥补一下空缺。

其数学表达式为:k = p / gcd(p, q)

表达式的意思,求p和q的最大公约数,然后p/最大公约数,就得到k,q也一样,如果p和q都是奇数,则会投射到1,如果只有p是奇数则会投射到0,否则会投射到2.至于数学原理,我并不理解,但是验证了一下确实是这样的,读者如果有更好的解释,可以跟我交流,时间复杂度度O(log(P)),空间复杂度O(1)。

problem

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 1:

Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.

Note:

1. 1 <= p <= 1000

2. 0 <= q <= p

Solution

class Solution {
public:
    int mirrorReflection(int p, int q) {
        int g=gcd(p,q);
        p/=g;p%=2;
        q/=g;q%=2;
        if(p==1&&q==1) return 1;
        return p==1 ? 0:2;
    }
    int gcd(int p,int q){
        return q==0 ? p:gcd(q,p%q);
    }
};

参考文献

[1]. 858. Mirror Reflection.https://leetcode.com/problems/mirror-reflection/solution/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值