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 _thelength of _n. If there is no such n, return -1.
We want the smallest number consisting only of 1’s that is divisible by k. Instead of constructing the number, we can keep track of the remainder when dividing by k as we “append” 1’s. If the remainder repeats, we are in a cycle and will never reach 0 (no such number exists).
classSolution {
public:int smallestRepunitDivByK(int k) {
int rem =0;
for (int len =1; len <= k; ++len) {
rem = (rem *10+1) % k;
if (rem ==0) return len;
}
return-1;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintsmallestRepunitDivByK(int k) {
int rem = 0;
for (int len = 1; len <= k; ++len) {
rem = (rem * 10 + 1) % k;
if (rem == 0) return len;
}
return-1;
}
}
1
2
3
4
5
6
7
8
classSolution:
defsmallestRepunitDivByK(self, k: int) -> int:
rem =0for length in range(1, k+1):
rem = (rem *10+1) % k
if rem ==0:
return length
return-1