Skip to content

Commit 3744fa2

Browse files
authored
feat: add solutions to lc problem: No.1015 (#4858)
1 parent 132a326 commit 3744fa2

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

solution/1000-1099/1015.Smallest Integer Divisible by K/README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,23 @@ function smallestRepunitDivByK(k: number): number {
150150
}
151151
```
152152

153+
#### Rust
154+
155+
```rust
156+
impl Solution {
157+
pub fn smallest_repunit_div_by_k(k: i32) -> i32 {
158+
let mut n = 1 % k;
159+
for i in 1..=k {
160+
if n == 0 {
161+
return i;
162+
}
163+
n = (n * 10 + 1) % k;
164+
}
165+
-1
166+
}
167+
}
168+
```
169+
153170
<!-- tabs:end -->
154171

155172
<!-- solution:end -->

solution/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,13 @@ tags:
6363

6464
<!-- solution:start -->
6565

66-
### Solution 1
66+
### Solution 1: Mathematics
67+
68+
We observe that the positive integer $n$ starts with an initial value of $1$, and each time it is multiplied by $10$ and then $1$ is added, i.e., $n = n \times 10 + 1$. Since $(n \times 10 + 1) \bmod k = ((n \bmod k) \times 10 + 1) \bmod k$, we can determine whether $n$ is divisible by $k$ by calculating $n \bmod k$.
69+
70+
We start from $n = 1$ and calculate $n \bmod k$ each time until $n \bmod k = 0$. At this point, $n$ is the smallest positive integer we are looking for, and its length is the number of digits in $n$. Otherwise, we update $n = (n \times 10 + 1) \bmod k$. If after looping $k$ times we still haven't found $n \bmod k = 0$, it means no such $n$ exists, and we return $-1$.
71+
72+
The time complexity is $O(k)$ and the space complexity is $O(1)$, where $k$ is the given positive integer.
6773

6874
<!-- tabs:start -->
6975

@@ -145,6 +151,23 @@ function smallestRepunitDivByK(k: number): number {
145151
}
146152
```
147153

154+
#### Rust
155+
156+
```rust
157+
impl Solution {
158+
pub fn smallest_repunit_div_by_k(k: i32) -> i32 {
159+
let mut n = 1 % k;
160+
for i in 1..=k {
161+
if n == 0 {
162+
return i;
163+
}
164+
n = (n * 10 + 1) % k;
165+
}
166+
-1
167+
}
168+
}
169+
```
170+
148171
<!-- tabs:end -->
149172

150173
<!-- solution:end -->
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
impl Solution {
2+
pub fn smallest_repunit_div_by_k(k: i32) -> i32 {
3+
let mut n = 1 % k;
4+
for i in 1..=k {
5+
if n == 0 {
6+
return i;
7+
}
8+
n = (n * 10 + 1) % k;
9+
}
10+
-1
11+
}
12+
}

0 commit comments

Comments
 (0)