在线时间:8:00-16:00
迪恩网络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 The square room has walls of length 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:
有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角以外,每个角落都放有一个接受器,编号为 正方形房间的墙壁长度为 返回光线最先遇到的接收器的编号(保证光线最终会遇到一个接收器)。 示例: 输入: p = 2, q = 1 输出: 2 解释: 这条光线在第一次被反射回左边的墙时就遇到了接收器 2 。
提示:
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 }
|
请发表评论