首页 > 其他 > 详细

1015. Smallest Integer Divisible by K (M)

时间:2020-11-25 22:28:44      阅读:31      评论:0      收藏:0      [点我收藏+]

Smallest Integer Divisible by K (M)

题目

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

题意

找出一个最长的全部由1组成的整数N,使其能被K整除。

思路

由于N的长度不定,不能直接用普通遍历去做。记由n个1组成的整数为\(f(n)\),而\(f(n)\)除以K的余数为\(g(n)\),则有\(g(n+1)=(g(n)*10+1)\%k\),下证:

\[\begin{cases} f(n)\div K=a \g(n)=f(n)\ \%\ K \f(n+1)=f(n)\times10+1 \g(n+1)=f(n+1)\ \%\ K \end{cases} \ \Rightarrow\ \begin{cases} f(n)=a\times K\ +g(n) \g(n+1)=(f(n)\times10+1)\ \%\ K \end{cases} \ \Rightarrow\ g(n+1)=(10a \times K + 10 \times g(n)+1)\ \%\ K \equiv (10\times g(n)+1)\ \%\ K \]

所以可以每次都用余数去处理。

另一个问题是确定循环的次数。对于除数K,得到的余数最多有0~K-1这K种情况,因此当我们循环K次都没有找到整除时,其中一定有重复的余数,这意味着之后的循环也不可能整除。所以最多循环K-1次。


代码实现

Java

class Solution {
    public int smallestRepunitDivByK(int K) {
        if (K % 5 == 0 || K % 2 == 0) {
            return -1;
        }
        
        int len = 1, n = 1;
        for (int i = 0; i < K; i++) {
            if (n % K == 0) {
                return len;
            }
            len++;
            n = (n * 10 + 1) % K;
        }

        return -1;
    }
}

1015. Smallest Integer Divisible by K (M)

原文:https://www.cnblogs.com/mapoos/p/14038256.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!