Skip to content

Commit

Permalink
Merge pull request #1004 from 0xff-dev/1492
Browse files Browse the repository at this point in the history
Add solution and test-cases for problem 1492
  • Loading branch information
6boris authored Oct 30, 2024
2 parents 948285c + c9e768c commit c632db8
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 12 deletions.
37 changes: 37 additions & 0 deletions leetcode/1401-1500/1492.The-kth-Factor-of-n/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# [1492.The kth Factor of n][title]

## Description
You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.

Consider a list of all factors of `n` sorted in **ascending order**, return the `kth` factor in this list or return `-1` if n has less than `k` factors.

**Example 1:**

```
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
```

**Example 2:**

```
Input: n = 7, k = 2
Output: 7
Explanation: Factors list is [1, 7], the 2nd factor is 7.
```

**Example 3:**

```
Input: n = 4, k = 4
Output: -1
Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/the-kth-factor-of-n/
[me]: https://github.com/kylesliu/awesome-golang-algorithm
13 changes: 11 additions & 2 deletions leetcode/1401-1500/1492.The-kth-Factor-of-n/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(n int, k int) int {
i := 1
for ; i <= n; i++ {
if n%i == 0 {
k--
if k == 0 {
return i
}
}
}
return -1
}
20 changes: 10 additions & 10 deletions leetcode/1401-1500/1492.The-kth-Factor-of-n/Solution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,30 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
n, k int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", 12, 3, 3},
{"TestCase2", 7, 2, 7},
{"TestCase3", 4, 4, -1},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
got := Solution(c.n, c.k)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
c.expect, got, c.n, c.k)
}
})
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}

0 comments on commit c632db8

Please sign in to comment.