1022. Smallest Integer Divisible by K

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/88775426

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
    

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/88775426
今日推荐