leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 2e0c50092c4094ed3262e8631dbb57e87f4bf5a5
parent 441a61937d0fe800e01d78999850affb39e8e88b
Author: Jack Sangdahl <jack@pngu.org>
Date:   Mon, 24 Nov 2025 18:30:31 -0700

1015. smallest integer divisible by k

Diffstat:
Asmallest_int_div_k.c | 22++++++++++++++++++++++
Asmallest_int_div_k.py | 30++++++++++++++++++++++++++++++
2 files changed, 52 insertions(+), 0 deletions(-)

diff --git a/smallest_int_div_k.c b/smallest_int_div_k.c @@ -0,0 +1,22 @@ +// 1015. Smallest Integer Divisible by K +#include "leetcode.h" + +/* + * given a positive integer 'k', you need to find the length of the smallest + * positive intger '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. + */ + +int smallestRepunitDivByK(int k) { + for (int i = 0, j = 1; j <= k; ++j) + if (!(i = (i * 10 + 1) % k)) + return j; + return -1; +} + +int main() { + printf("%d\n", smallestRepunitDivByK(1)); // expect: 1 + printf("%d\n", smallestRepunitDivByK(2)); // expect: -1 + printf("%d\n", smallestRepunitDivByK(3)); // expect: 3 +} diff --git a/smallest_int_div_k.py b/smallest_int_div_k.py @@ -0,0 +1,30 @@ +# 1015. Smallest Integer Divisible by K + +""" +given a positive integer 'k', you need to find the length of the smallest +positive intger '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. +""" + + +class Solution(object): + def smallestRepunitDivByK(self, k): + """ + :type k: int + :rtype: int + """ + if k % 2 == 0 or k % 5 == 0: + return -1 + i = 0 + for j in range(1, k + 1): + i = (i * 10 + 1) % k + if not i: + return j + + +if __name__ == "__main__": + obj = Solution() + print(obj.smallestRepunitDivByK(k=1)) + print(obj.smallestRepunitDivByK(k=2)) + print(obj.smallestRepunitDivByK(k=3))