[Swift]LeetCode858. 镜面反射 | Mirror Reflection

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-cbfuhwmh-me.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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 01, and 2.git

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.github

Return the number of the receptor that the ray meets first.  (It is guaranteed that the ray will meet a receptor eventually.) 微信

Example 1:spa

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

  1. 1 <= p <= 1000
  2. 0 <= q <= p

有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角之外,每一个角落都放有一个接受器,编号为 0, 1,以及 2htm

正方形房间的墙壁长度为 p,一束激光从西南角射出,首先会与东墙相遇,入射点到接收器 0 的距离为 q 。blog

返回光线最早遇到的接收器的编号(保证光线最终会遇到一个接收器)。 ci

示例:rem

输入: p = 2, q = 1
输出: 2
解释: 这条光线在第一次被反射回左边的墙时就遇到了接收器 2 。

 

提示:

  1. 1 <= p <= 1000
  2. 0 <= q <= p

Runtime: 4 ms
Memory Usage: 18.5 MB
 1 class Solution {
 2     func mirrorReflection(_ p: Int, _ q: Int) -> Int {
 3         var p = p
 4         var q = q
 5         while (p % 2 == 0 && q % 2 == 0)
 6         {
 7             p /= 2
 8             q /= 2
 9         }
10         if p % 2 == 0
11         {
12             return 2
13         }
14         else if q % 2 == 0
15         {
16             return 0
17         }
18         else
19         {
20              return 1
21         }
22     }
23 }

4ms

 1 final class Solution {
 2     func mirrorReflection(_ p: Int, _ q: Int) -> Int {
 3         var curQ = 0
 4         var count = 0
 5         var opposite = false
 6         while curQ != p {
 7             curQ &+= q
 8             count &+= 1
 9             if curQ > p {
10                 curQ &-= p
11                 opposite = !opposite
12             }
13         }
14         if opposite { return 0 }
15         return count % 2 == 1 ? 1 : 2
16     }
17 }

8ms

 1 class Solution {
 2     func mirrorReflection(_ p: Int, _ q: Int) -> Int {
 3         var n=1
 4         while Double(n*q)/Double(p)-Double(n*q/p) != 0 {
 5             n+=1
 6         }
 7         if Double(n*q/p)/Double(2) - Double(n*q/(2*p))==0 {
 8             return Double(n)/Double(2) - Double(n/2)==0 ? -1:0
 9         }else{
10             return Double(n)/Double(2) - Double(n/2)==0 ? 2:1
11         }
12     }
13 }
相关文章
相关标签/搜索