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.
找出由1组成的数字,这个数字能被k整除,返回数字的长度。
思路:
能被2整除的数肯定是偶数,被5整除的数最后一位是0或5.
所以只要是2或5的倍数,直接返回-1
参考该文:有一个定理,若K不能被2或5整除,则一定有一个长度小于等于K且均由1组成的数,可以整除K。每次乘以 10 再加1,就可以得到下一个数字,但是由于K可能很大,则N就会超出整型数的范围,就算是长整型也不一定 hold 的住,所以不能一直变大,而是每次累加后都要对 K 取余,若余数为0,则直接返回当前长度,若不为0,则用余数乘以 10 再加1,这好像也是用到了余数的一些性质,总之这道题主要就是考察数学知识,跟算法关系不太大。
public int smallestRepunitDivByK(int k) {
if(k % 2 == 0 || k % 5 == 0) return -1;
int val = 1;
for(int i = 1; i <= k; i++) {
if(val % k == 0) return i;
val = (val*10 + 1) % k;
}
return -1;
}