Description
Given a positive integer K, you need to find the length of 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.
Note: N may not fit in a 64-bit signed integer.
Example 1:
Input: K = 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.
Example 2:
Input: K = 2
Output: -1
Explanation: There is no such positive integer N divisible by 2.
Example 3:
Input: K = 3
Output: 3
Explanation: The smallest answer is N = 111, which has length 3.
Constraints:
- 1 <= K <= 105
分析
题目的意思是:给定数K,求最小的数N,能够整除K,N只包含1。如果只包含1的话,思路也就很直接了,把所有的只包含1的数列觉出来,然后一个一个的判断就行了。还有个规律是N的长度不会超过K。
如果K的尾数是2,4,5,6,8的话,一定不存在N。简单说明:要求的N结尾一定是1,那么一定不能被2的倍数整除,被5整除的数字的结尾必须是0或者5。
- 如果这K个余数中有一个余数是0,那么当前的N能被K整除直接返回。
- 如果这K个余数中都不为0时,一定有重复的余数!我们知道一个数对K的余数只能是0 ~ K - 1其中的一个,所以如果K个数字的余数中没有0,那么肯定有重复的余数。如果出现重复的余数,那么后面再增大N时,对K的余数就会形成循环,则再也不可能出现余数为0的情况。
总之,如果遍历到了长度为K的N时仍然不存在余数是0,那么后面就不用搜索了
代码
class Solution:
def smallestRepunitDivByK(self, K: int) -> int:
N=0
for i in range(1,K+1):
N=N*10+1
if(N%K==0):
return i
return -1
class Solution:
def smallestRepunitDivByK(self, K: int) -> int:
N=0
if(K%10 in [2,4,5,6,8]):
return -1
for i in range(1,K+1):
N=N*10+1
if(N%K==0):
return i
return -1
参考文献
solution
【LeetCode】1022. Smallest Integer Divisible by K 解题报告(Python)