1015. Smallest Integer Divisible by K (M)

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.java

Return the length of N. If there is no such N, return -1.git

Note: N may not fit in a 64-bit signed integer.ui

Example 1:spa

Input: K = 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.

Example 2:code

Input: K = 2
Output: -1
Explanation: There is no such positive integer N divisible by 2.

Example 3:it

Input: K = 3
Output: 3
Explanation: The smallest answer is N = 111, which has length 3.

Constraints:io

  • 1 <= K <= 10^5

題意

找出一個最長的所有由1組成的整數N,使其能被K整除。class

思路

因爲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;
    }
}
相關文章
相關標籤/搜索