[leetcode] 1015. Smallest Integer Divisible by K

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. 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。

  1. 如果这K个余数中有一个余数是0,那么当前的N能被K整除直接返回。
  2. 如果这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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值