leetcode 400. Nth Digit
来源:互联网 发布:思源软件 编辑:程序博客网 时间:2024/05/23 22:02
1.题目
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …
有这样一个无限序列,求这个序列的第n个数字是多少。
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
2.分析
第一步,确定第n个数字所在的number是多少。也就是从1开始数,累积每个数的位数,直到和大于等于n。
1-9 每个数长度为1 总长 9*1
10-99 每个数长度为2 总长 90*2
100-999 每个数长度为3 总长900*3
。。。
9*pow(10,i-1)*i
第二步,确定n在number的哪一位上。
3.代码
class Solution {public: int findNthDigit(int n) { if (n < 10) return n; long long sum = 0; int i = 1; while (n > sum) { sum += 9 * i*pow(10, i - 1); ++i; } i -= 1; int remain = n - (sum - 9 * i*pow(10, i - 1)); int number = pow(10, i - 1) + (remain - 1) / i;//找出所在的数 int c = remain%i == 0 ? 0 : i - remain%i;//所在的位 while (c) { number = number / 10; --c; } return number % 10; }};
阅读全文
0 0
- 【Leetcode】400. Nth Digit
- leetcode 400. Nth Digit
- 400. Nth Digit (leetcode) 。。。
- [LeetCode]400. Nth Digit
- [leetcode] 400. Nth Digit
- [LeetCode]--400. Nth Digit
- leetcode 400. Nth Digit
- LeetCode 400. Nth Digit
- [leetcode]400. Nth Digit
- Leetcode 400. Nth Digit
- LeetCode 400. Nth Digit
- 【LeetCode】 400. Nth Digit
- LeetCode 400. Nth Digit
- LeetCode 400. Nth Digit
- LeetCode 400. Nth Digit
- LeetCode-400. Nth Digit
- [LeetCode]400. Nth Digit
- 【Leetcode】400. Nth Digit
- 斐讯k2路由器刷pandorabox认证哆点Drcom
- Java反射机制总结
- 文本编辑器添加右键打开方式
- JavaScript对象,思维导图
- 【bzoj1827】[Usaco2010 Mar]gather 奶牛大集会 树形dp+贪心
- leetcode 400. Nth Digit
- 【Mybatis升级版-04】包装类型pojo参数绑定
- springmvc常用注解
- MissionPlanner找不到全部参数表(Full Parameter List)的解决方法
- vue实例生命周期易错点
- hdu3572 Task Schedule(最大流dinic)
- C#接口--C#基础
- Android disable strictmode
- Linux通过命令下载文件