为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode1015. 可被 K 整除的最小整数 | Smallest Integer Divisible by K

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10587885.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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: 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 <= 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 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 }

 

posted @ 2019-03-24 13:33  为敢技术  阅读(1091)  评论(0编辑  收藏  举报