0
点赞
收藏
分享

微信扫一扫

【LeetCode】1022. Smallest Integer Divisible by K 解题报告(Python)

_刘彦辉 2022-02-10 阅读 27


id: fuxuemingzhu

个人博客: ​​​http://fuxuemingzhu.cn/​​​


目录


  • ​​题目描述​​
  • ​​题目大意​​
  • ​​解题方法​​
  • ​​日期​​


题目地址:​​https://leetcode.com/problems/smallest-integer-divisible-by-k/​​

题目描述

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. ​1 <= K <= 10^5​

题目大意

给了一个整数K,现在要求一个全部由1构成的十进制整数N,使得N能被K整除,并且要求返回最小满足条件的N的位数。如果N不存在,则返回-1.

解题方法

这个题有点不好想,如果不去考虑技巧的话,根本想不出来还有什么解法。

首先,如果K的尾数是​​2,4,5,6,8​​的话,一定不存在N。简单说明:我们要求的N结尾一定是1,那么一定不能被2的倍数整除。另外我们知道能被5整除的数字的结尾必须是0或者5,所以得证。

然后,我们要证明N的长度不会超过K。

我们要判断对于每个N其对K的余数:​​1 % K, 11 % K, 111 % K, ..., 11...1 (K '1's) % K.​


  1. 如果这K个余数中有一个余数是0,那么当前的N能被K整除直接返回。
  2. 如果这K个余数中都不为0时,一定有重复的余数!我们知道一个数对K的余数只能是​​0 ~ K - 1​​其中的一个,所以如果K个数字的余数中没有0,那么肯定有重复的余数。如果出现重复的余数,那么后面再增大N时,对K的余数就会形成循环,则再也不可能出现余数为0的情况。

总之,如果遍历到了长度为K的N时仍然不存在余数是0,那么后面就不用搜索了。

举个例子,我们发现​​长度 <= 6 = K​​的N的余数是循环的。


  • 1 % 6 = 1
  • 11 % 6 = 5
  • 111 % 6 = 3
  • 1111 % 6 = 1
  • 11111 % 6 = 5
  • 111111 % 6 = 3

严谨的证明应该是如果​​N2 % K == N1 % K​​​的话,证明​​(10 * N2 + 1) % K == (10 * N1 + 1) % K​​. 留给读者证明吧。

另外,我们在求的过程中,并不是直接维护的N,而是维护的​​N % K​​​,这里的假设是​​(10 * N + 1) % K​​​的变化规律和​​(10 * (N % K) + 1) % K​​变化规律一致。

Python代码如下:

class Solution(object):
def smallestRepunitDivByK(self, K):
"""
:type K: int
:rtype: int
"""
if K % 10 not in {1, 3, 7, 9}: return -1
r = 0
for i in range(1, K + 1):
r = (10 * r + 1) % K
if r == 0:
return i
return -1

参考资料:​​https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/260875/Python-O(K)-with-Detailed-Explanations​​

日期

2019 年 3 月 24 日 —— 这个周赛太悲催了



举报

相关推荐

0 条评论