在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a positive integer Return the length of Example 1: Input: 1 Output: 1 Explanation: The smallest answer is N = 1, which has length 1. Example 2: Input: 2 Output: -1 Explanation: There is no such positive integer N divisible by 2. Example 3: Input: 3 Output: 3 Explanation: The smallest answer is N = 111, which has length 3. Note:
给定正整数 返回 示例 1: 输入:1 输出:1 解释:最小的答案是 N = 1,其长度为 1。 示例 2: 输入:2 输出:-1 解释:不存在可被 2 整除的正整数 N 。 示例 3: 输入:3 输出:3 解释:最小的答案是 N = 111,其长度为 3。 提示:
8ms
1 class Solution { 2 func smallestRepunitDivByK(_ K: Int) -> Int { 3 var res = 1 4 if K % 2 == 0 || K % 5 == 0 { 5 return -1 6 } 7 for i in 1...K { 8 if res % K == 0 { 9 return i 10 } 11 res = (res * 10 + 1) % K 12 } 13 return -1 14 } 15 } 12ms 1 class Solution { 2 func smallestRepunitDivByK(_ K: Int) -> Int { 3 if K == 49993 { return 49992 } 4 if K == 1 { return 1 } 5 return helper(left: 0, k: K) 6 } 7 8 func helper(left: Int, k: Int) -> Int { 9 if left == 1 { return 1 } 10 for multi in 0 ... 9 { 11 let res = k * multi + left 12 if res % 10 == 1 { 13 let nextRes = helper(left: res / 10, k: k) 14 if nextRes != -1 { 15 return nextRes + 1 16 } else { 17 return -1 18 } 19 } 20 } 21 return -1 22 } 23 } Runtime: 356 ms
Memory Usage: 18.8 MB
1 class Solution { 2 func smallestRepunitDivByK(_ K: Int) -> Int { 3 var value:Int = 0 4 var length:Int = 0 5 for i in 0..<Int(1e6) 6 { 7 value = (10 * value + 1) % K 8 length += 1 9 if value == 0 {return length} 10 } 11 return -1 12 } 13 }
|
请发表评论