[LeetCode] 1015. Smallest Integer Divisible by K 可以整除K的最小整數



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 <= 105

這道題說是給了一個正整數K,讓找到一個長度最短且只由1組成的正整數N,可以整除K,問最短的長度是多少,若沒有,則返回 -1。關於整除的一些性質,博主記得小學就應該學過,比如能被2整除的數字必須是偶數,能被3整除的數字各個位加起來必須能被3整除,能被5整除的數字的末尾數字必須是0或者5。由於N都是由1組成的,所以一定不可能整除2或者5,所以只要K中包含2或者5,直接返回 -1。其實有一個定理,若K不能被2或5整除,則一定有一個長度小於等於K且均由1組成的數,可以整除K。具體的證明博主就不講了,可以參見論壇上的帖子。這里只要找到那個最短的長度即可,就從1開始試唄,每次乘以 10 再加1,就可以得到下一個數字,但是由於K可能很大,則N就會超出整型數的范圍,就算是長整型也不一定 hold 的住,所以不能一直變大,而是每次累加后都要對 K 取余,若余數為0,則直接返回當前長度,若不為0,則用余數乘以 10 再加1,這好像也是用到了余數的一些性質,總之這道題主要就是考察數學知識,跟算法關系不太大,若面試遇到的話,只能自求多福了,參見代碼如下:


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

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1015


參考資料:

https://leetcode.com/problems/smallest-integer-divisible-by-k/

https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/260852/JavaC%2B%2BPython-O(1)-Space-with-Proves-of-Pigeon-Holes

https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/260916/Proof%3A-we-only-need-to-consider-the-first-K-candidates-in-1-11-111-1111-...


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM