[LeetCode] Smallest Integer Divisible by K

1015. Smallest Integer Divisible by 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int smallestRepunitDivByK(int k) {
if(!(k & 1)) return -1;
unordered_set<int> s;
int res = 1, power = 1;
while(true) {
int remainder = power % k;
if(!remainder) return res;
if(!s.insert(remainder).second) return -1;
power = remainder * 10 + 1;
res++;
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/smallest-integer-divisible-by-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.