400. Nth Digit
2017-12-28 12:47
141 查看
1、题目描述
所有正整数都连在一块,返回第n位的数字是啥。
2、思路
1位数字有9个;
2位数组有90个;
3位。。。900个;
k位。。。9*pow(10,k-1)
先判断第n位所在的位置应该是几位数k,此时n把前面的数字都减去还剩几位数n。
问题简化为找k位数字排到一块的第n位数字。
计算n/k and n%k;
1)n%k=0,说明答案正好落在第n/k个数字的最后1位上。
2)n%k!=0,说明答案落在第n/k+1个数字的从左往右数的第n%k位上。
3、代码
所有正整数都连在一块,返回第n位的数字是啥。
2、思路
1位数字有9个;
2位数组有90个;
3位。。。900个;
k位。。。9*pow(10,k-1)
先判断第n位所在的位置应该是几位数k,此时n把前面的数字都减去还剩几位数n。
问题简化为找k位数字排到一块的第n位数字。
计算n/k and n%k;
1)n%k=0,说明答案正好落在第n/k个数字的最后1位上。
2)n%k!=0,说明答案落在第n/k+1个数字的从左往右数的第n%k位上。
3、代码
int findNthDigit(int n) { long long x = 9; long long k=1; while(n-x*k>0){ n=n-x*k; x=x*10; k++; } int th = n/k; int th2 = n%k; long long ans = 1; for(int i=1;i<k;i++) ans*=10; if(th2==0){ ans=ans+th-1; return ans%10; } else{ ans+=th; for (int i = th2; i < k; i ++) ans /= 10; return ans % 10; } }
相关文章推荐
- Leetcode 400. Nth Digit (Easy) (cpp)
- 400. Nth Digit (leetcode) 。。。
- LeetCode | 400. Nth Digit 数学原理题
- LeetCode 400. Nth Digit
- 【C语言】 LeetCode 400. Nth Digit
- LeetCode - 400. Nth Digit
- 【leetcode】400. Nth Digit(Python & C++)
- 400. Nth Digit
- 【Leetcode】400. Nth Digit
- leetcode 400. Nth Digit
- Leetcode 400. Nth Digit 第n个数字 解题报告
- 400. Nth Digit
- leetcode 400. Nth Digit 从1到n第n位数字是什么 + 找规律
- [leetcode] 400. Nth Digit 解题报告
- LeetCode 400. Nth Digit
- leetcode 400. Nth Digit
- leetcode 400. Nth Digit
- 400. Nth Digit
- leetcode_400. Nth Digit 查找自然数序列中的第n个数字
- [LeetCode]400. Nth Digit(规律)