Skip to content

Commit

Permalink
Merge pull request #990 from 0xff-dev/400
Browse files Browse the repository at this point in the history
Add solution and test-cases for problem 400
  • Loading branch information
6boris authored Oct 30, 2024
2 parents 68a2faf + aa81921 commit 94117b6
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 9 deletions.
26 changes: 26 additions & 0 deletions leetcode/301-400/0400.Nth-Digit/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# [400. Nth Digit][title]

## Description
Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`.

**Example 1:**

```
Input: n = 3
Output: 3
```

**Example 2:**

```
Input: n = 11
Output: 0
Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
```

## 结语

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

[title]: https://leetcode.com/problems/nth-digit
[me]: https://github.com/kylesliu/awesome-golang-algorithm
27 changes: 25 additions & 2 deletions leetcode/301-400/0400.Nth-Digit/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(n int) int {
if n <= 9 {
return n
}
fixed := 9
base, pow := 1, 1
cur := base * pow * fixed
for cur < n {
n -= cur
base, pow = base+1, pow*10
cur = base * pow * fixed
}
need := n / base
target := pow + (need - 1)
mod := n % base
if mod == 0 {
return target % 10
}

shift := base - mod
target++
for ; shift > 0; shift-- {
target /= 10
}
return target % 10
}
13 changes: 6 additions & 7 deletions leetcode/301-400/0400.Nth-Digit/Solution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", 3, 3},
{"TestCase2", 11, 0},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

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

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

0 comments on commit 94117b6

Please sign in to comment.