题目:
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
思路:
有点数学题的感觉,题目大意是给定K,找出最小的N,N能被K整除,返回N的长度,如果没有这种N则返回-1。常规逻辑肯定是不断增大N,如果找到能整除的就就返回,那么问题就在于什么时候停止。首先先排除corner case,如果K能被2整除或者被5整除,那么N的个位数肯定不能是1,因此这两种情况的K排除。其次什么时候停止?答案应该是N的长度不大于K,假设N=K,这种情况下,共有K个余数,如果其中没有被整除的情况,那么就出现了鸽笼问题。一个数对K的余数应该是[0, K-1],如果没有出现0,那么肯定出现了重复数。如果有重复的话,那么再增大N也只是增加一轮,并不会获得被整除的数,就没有必要继续增大了。具体实现用一个r来记录余数,然后用N来记录位数,如果遇到整除则返回N即可。这里维护r的原因是认为(10*N+1)%K和(10*(N%K)+1)%K变化规律相同。
代码:
class Solution {
public:
int smallestRepunitDivByK(int K) {
if(K%2==0||K%5==0)
return -1;
int r=0;
for(int N=1;N<=K;N++)
{
r=(r*10+1)%K;
if(r==0)
return N;
}
return -1;
}
};