★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝()➤GitHub地址:➤原文地址: ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★Given a positive integer K
, you need find the smallest positive integer N
such that N
is divisible by K
, and N
only contains the digit 1.
Return the length of N
. If there is no such N
, return -1.
Example 1:
Input: 1Output: 1Explanation: The smallest answer is N = 1, which has length 1.
Example 2:
Input: 2Output: -1Explanation: There is no such positive integer N divisible by 2.
Example 3:
Input: 3Output: 3Explanation: The smallest answer is N = 111, which has length 3.
Note:
1 <= K <= 10^5
给定正整数 K
,你需要找出可以被 K 整除的、仅包含数字 1 的最小正整数 N。
返回 N
的长度。如果不存在这样的 N
,就返回 -1
。
示例 1:
输入:1输出:1解释:最小的答案是 N = 1,其长度为 1。
示例 2:
输入:2输出:-1解释:不存在可被 2 整除的正整数 N 。
示例 3:
输入:3输出:3解释:最小的答案是 N = 111,其长度为 3。
提示:
1 <= K <= 10^5
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 i10 }11 res = (res * 10 + 1) % K12 }13 return -114 }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 + left12 if res % 10 == 1 {13 let nextRes = helper(left: res / 10, k: k)14 if nextRes != -1 {15 return nextRes + 116 } else {17 return -118 }19 }20 } 21 return -122 } 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..