1015.Smallest Integer Divisible by K(可被 K 整除的最小整数)

Description

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.


给定正整数 K,你需要找出可以被 K 整除的、仅包含数字 1 的最小正整数 N

返回 N 的长度。如果不存在这样的 N,就返回 -1

题目链接:https://leetcode.com/problems/smallest-integer-divisible-by-k/

Difficulty: medium

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

分析

  • 已知任意数字的个位数为li=[1,3,7,9]中任意一个,其任意倍数的个位数不可能为1;
  • 若K的个位数在li中,返回-1;
  • 反之,N表示n位长的数字且每一位都为“1”,判断是否可以整除K;
  • 若整除,返回N的长度,反之,长度加一,回到上一步。

参考代码

class Solution(object):
def smallestRepunitDivByK(self, K):
    li=[1,3,7,9]
    if(K%10 not in li):
        return -1
    index=1
    N=1
    while(N%K != 0):
        index+=1
        N=N*10+1
    return index
-------------本文结束你这么美,还坚持读完了-------------