Merge pull request #203 from gostool/leetcode0400

Leetcode0400
This commit is contained in:
halfrost
2021-12-22 19:08:01 -08:00
committed by GitHub
3 changed files with 130 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package leetcode
import "math"
func findNthDigit(n int) int {
if n <= 9 {
return n
}
bits := 1
for n > 9*int(math.Pow10(bits-1))*bits {
n -= 9 * int(math.Pow10(bits-1)) * bits
bits++
}
idx := n - 1
start := int(math.Pow10(bits - 1))
num := start + idx/bits
digitIdx := idx % bits
return num / int(math.Pow10(bits-digitIdx-1)) % 10
}

View File

@ -0,0 +1,45 @@
package leetcode
import (
"fmt"
"testing"
)
type question400 struct {
para400
ans400
}
// para 是参数
type para400 struct {
n int
}
// ans 是答案
type ans400 struct {
ans int
}
func Test_Problem400(t *testing.T) {
qs := []question400{
{
para400{3},
ans400{3},
},
{
para400{11},
ans400{0},
},
}
fmt.Printf("------------------------Leetcode Problem 400------------------------\n")
for _, q := range qs {
_, p := q.ans400, q.para400
fmt.Printf("【input】:%v 【output】:%v\n", p.n, findNthDigit(p.n))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,66 @@
# [400. Nth Digit](https://leetcode-cn.com/problems/nth-digit/)
## 题目
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.
**Constraints:**
- 1 <= n <= int(math.Pow(2, 31)) - 1
## 题目大意
给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位数字。
## 解题思路
- bits = 1的时候有1,2,3,4,5,6,7,8,9这9个数;9 = math.Pow10(bits - 1) * bits
- bits = 2的时候有10-99这90个数;90 = math.Pow10(bits - 1) * bits
- n不断减去bits从1开始的数字总数,求出n所在的数字是几位数即bits
- 计算n所在的数字num等于初始值加上(n - 1) / bits
- 计算n所在这个数字的第几位digitIdx等于(n - 1) % bits
- 计算出digitIdx位的数字
### 以11为例:
11 - 9 = 2
(2 - 1) / 2 = 0
(2 - 1) % 2 = 1
也就是说第11位数字是位数是2的第一个数字的第二位即是0
## 代码
```go
package leetcode
import "math"
func findNthDigit(n int) int {
if n <= 9 {
return n
}
bits := 1
for n > 9*int(math.Pow10(bits-1))*bits {
n -= 9 * int(math.Pow10(bits-1)) * bits
bits++
}
idx := n - 1
start := int(math.Pow10(bits - 1))
num := start + idx/bits
digitIdx := idx % bits
return num / int(math.Pow10(bits-digitIdx-1)) % 10
}
```