LeetCode 858 题解

https://leetcode.com/problems/mirror-reflection/description/

题目大意:一个正方形的空间,边长为p,从左下角向右斜上方射出一条光线,形成的三角形的另外一边为q,问反射多次后,光线第一次打到角上的位置。

解题思路:将正方形拉长,求p,q的最小公倍数。注意q为0的情况。

class Solution {
    private int gcd(int a,int b) {
        return b==0?a:gcd(b,a%b);
    }
    public int mirrorReflection(int p, int q) {
        int n = p*q / gcd(p,q);
        if(q==0) return 0;
        int m1 = n/q;
        int m2 = n/p;
//        System.out.println(m1+" "+m2);
        if(m1%2==0 && m2%2==1) return 2;
        if(m1%2==1 && m2%2==1) return 1;
        if(m1%2==1 && m2%2==0) return 0;
        if(m1%2==0 && m2%2==0) return 0;
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80944105