-
Notifications
You must be signed in to change notification settings - Fork 186
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #990 from 0xff-dev/400
Add solution and test-cases for problem 400
- Loading branch information
Showing
3 changed files
with
57 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters