1022. Smallest Integer Divisible by K

88 篇文章 0 订阅

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

Discuss

思路:直接暴力从1..1到约数,或者暴力从约数到1..1的搜索空间太大了,所以要考虑一些数学性质

因为N有固定的1..1 pattern,可以预见这些从小到大的N得到的余数会陷入一个循环,而且必然会陷入循环,因为余数可能性最多就K中,所以可以通过观测在进入循环之前有没有余数为0的情况

class Solution(object):
    def smallestRepunitDivByK(self, K):
        """
        :type K: int
        :rtype: int
        """
        if K%2==0 or K%5==0: return -1
        if K==1: return 1
        
        ss=set()
        yushu=1
        cnt=1
        while 1:
            yushu = (yushu*10+1)%K
            cnt+=1
            if yushu==0: return cnt
            if yushu in ss:
                return -1
            else:
                ss.add(yushu)
            
        return -1
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值