为有牺牲多壮志,敢教日月换新天。

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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10594963.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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.

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

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

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

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

示例:

输入: 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 }

 

posted @ 2019-03-25 17:18  为敢技术  阅读(261)  评论(0编辑  收藏  举报