★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-efciymil-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
Return the length of N
. If there is no such N
, return -1.github
Example 1:微信
Input: 1 Output: 1 Explanation: The smallest answer is N = 1, which has length 1.
Example 2:spa
Input: 2 Output: -1 Explanation: There is no such positive integer N divisible by 2.
Example 3:code
Input: 3 Output: 3 Explanation: The smallest answer is N = 111, which has length 3.
Note:htm
1 <= K <= 10^5
給定正整數 K
,你須要找出能夠被 K 整除的、僅包含數字 1 的最小正整數 N。blog
返回 N
的長度。若是不存在這樣的 N
,就返回 -1
。get
示例 1:博客
輸入:1 輸出:1 解釋:最小的答案是 N = 1,其長度爲 1。
示例 2:
輸入:2 輸出:-1 解釋:不存在可被 2 整除的正整數 N 。
示例 3:
輸入:3 輸出:3 解釋:最小的答案是 N = 111,其長度爲 3。
提示:
1 <= K <= 10^5
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 }
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 }