diff --git a/leetcode/301-400/0400.Nth-Digit/README.md b/leetcode/301-400/0400.Nth-Digit/README.md new file mode 100644 index 00000000..839e1bb5 --- /dev/null +++ b/leetcode/301-400/0400.Nth-Digit/README.md @@ -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 diff --git a/leetcode/301-400/0400.Nth-Digit/Solution.go b/leetcode/301-400/0400.Nth-Digit/Solution.go index d115ccf5..4156b285 100755 --- a/leetcode/301-400/0400.Nth-Digit/Solution.go +++ b/leetcode/301-400/0400.Nth-Digit/Solution.go @@ -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 } diff --git a/leetcode/301-400/0400.Nth-Digit/Solution_test.go b/leetcode/301-400/0400.Nth-Digit/Solution_test.go index 14ff50eb..c0c0d237 100755 --- a/leetcode/301-400/0400.Nth-Digit/Solution_test.go +++ b/leetcode/301-400/0400.Nth-Digit/Solution_test.go @@ -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}, } // 开始测试 @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }