Leetcode 400. Nth Digit 第n个数字 解题报告
2016-09-18 15:40
567 查看
1 解题思想
终于到了第400了这道题是说从1开始的第n个数字是什么,注意是数字而不是数
如:
12是一个数,有两个数字1,2
那么这题主要需要考虑第n个数是多少位的,然后是哪个数,数里面的哪个位置,而主要规律是:
* 这里首先分析一下位数和规律 * 个位数:1-9,一共9个,共计9个数字 * 2位数:10-99,一共90个,共计180个数字 * 3位数:100-999,一共900个,共计270个数字 * 4位数,1000-9999,一共9000个,共计36000个数字 * 以此类推, * 这样我们就可以首先定位到是哪个数,再找到其对应的数字
2 原题
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... Note: n is positive and will fit within the range of a 32-bit signed integer (n < 231). Example 1: Input: 3 Output: 3 Example 2: Input: 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.
3 AC解
public class Solution { /** * 这里是找第n个数字(这里的数和数字有区别,数字可以理解为将所有数拼合成一个字符串后的第n为对应的数字(0-9)) * 这里首先分析一下位数和规律 * 个位数:1-9,一共9个,共计9个数字 * 2位数:10-99,一共90个,共计180个数字 * 3位数:100-999,一共900个,共计270个数字 * 4位数,1000-9999,一共9000个,共计36000个数字 * 以此类推, * 这样我们就可以首先定位到是哪个数,再找到其对应的数字 * */ public int findNthDigit(int n) { //小心溢出 int digitType = 1; long digitNum = 9; //定位到是几位数 while(n > digitNum*digitType){ n -= (int) digitNum*digitType ; digitType++; digitNum*=10; } //定位到是这些几位数里面的第几个的第几位 int indexInSubRange = (n -1) / digitType; int indexInNum = (n -1) % digitType; //还原数字 int num = (int)Math.pow(10,digitType - 1) + indexInSubRange ; int result = Integer.parseInt((""+num).charAt(indexInNum)+""); return result; } }
相关文章推荐
- leetcode 400. Nth Digit解题报告
- [Leetcode] 400. Nth Digit 解题报告
- [leetcode] 400. Nth Digit 解题报告
- leetcode_400. Nth Digit 查找自然数序列中的第n个数字
- [leetcode] 233. Number of Digit One 解题报告
- Leetcode 65. Valid Number 验证数字 解题报告
- Leetcode 402. Remove K Digits 删除K个数字 解题报告
- Leetcode 412. Fizz Buzz 数字生成 解题报告
- [LeetCode]Number of Digit One,解题报告
- [Leetcode] 233. Number of Digit One 解题报告
- 400. Nth Digit (找第n个数字)
- Leetcode 423. Reconstruct Original Digits from English 重构数字 解题报告
- Leetcode 357. Count Numbers with Unique Digits 统计没有重复数字的数 解题报告
- 解题报告:LeetCode Search in Rotated Sorted Array II(循环数字查找)
- LeetCode-Number of Digit One-解题报告
- leetcode 400. Nth Digit 从1到n第n位数字是什么 + 找规律
- [LeetCode] Integer to Roman 解题报告
- [LeetCode] Implement strStr() 解题报告
- [LeetCode] Gray Code 解题报告
- [LeetCode] Jump Game 解题报告