在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ A positive integer is magical if it is divisible by either A or B. Return the N-th magical number. Since the answer may be very large, return it modulo Example 1: Input: N = 3
Output: 2
Example 2: Input: N = 3
Output: 6
Example 3: Input: N = 4
Output: 10
Example 4: Input: N = 4
Output: 8
Note:
如果正整数可以被 A 或 B 整除,那么它是神奇的。 返回第 N 个神奇数字。由于答案可能非常大,返回它模 示例 1: 输入:N = 1, A = 2, B = 3 输出:2 示例 2: 输入:N = 4, A = 2, B = 3 输出:6 示例 3: 输入:N = 5, A = 2, B = 4 输出:10 示例 4: 输入:N = 3, A = 6, B = 4 输出:8 提示:
Runtime: 4 ms
Memory Usage: 18.4 MB
1 class Solution { 2 func nthMagicalNumber(_ N: Int, _ A: Int, _ B: Int) -> Int { 3 var a:Int = A 4 var b:Int = B 5 var tmp:Int = 0 6 var l:Int = 2 7 var r:Int = Int(1e14) 8 var mod:Int = Int(1e9 + 7) 9 while (b > 0) 10 { 11 tmp = a 12 a = b 13 b = tmp % b 14 } 15 while (l < r) 16 { 17 var m:Int = (l + r) / 2; 18 if m / A + m / B - m / (A * B / a) < N 19 { 20 l = m + 1 21 } 22 else 23 { 24 r = m 25 } 26 } 27 return Int(l % mod) 28 } 29 }
|
请发表评论