★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 0
, 1
, 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 0
th 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 <= p <= 1000
0 <= q <= p
有一個特殊的正方形房間,每面牆上都有一面鏡子。除西南角之外,每一個角落都放有一個接受器,編號爲 0
, 1
,以及 2
。htm
正方形房間的牆壁長度爲 p
,一束激光從西南角射出,首先會與東牆相遇,入射點到接收器 0
的距離爲 q
。blog
返回光線最早遇到的接收器的編號(保證光線最終會遇到一個接收器)。 ci
示例:rem
輸入: p = 2, q = 1 輸出: 2 解釋: 這條光線在第一次被反射回左邊的牆時就遇到了接收器 2 。
提示:
1 <= p <= 1000
0 <= q <= p
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 }