[Leetcode] 400. Nth Digit 解题报告
来源:互联网 发布:淘宝卖办公用品 编辑:程序博客网 时间:2024/06/07 19:07
题目:
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:3Output:3
Example 2:
Input:11Output:0Explanation: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.
思路:
可以分为三步来计算:1)找出给定的n落在几位数的范围内;2)找出具体落在哪个数字上;3)找出具体在哪一位上。
一位数一共有9个,两位数一共有90个,三位数一共有900个,以此类推,因此可以每增加一位数字,看n是否在这个范围之内。我们以n = 150为例来具体说明:1)首先一位数有9个数字并且9 < 150,所以位数可以加1,这样 n - 9 = 141,然后两位数的数字有2 * 90 = 180位,大于141,所以目标数字肯定是在两位数上。2)求具体数字,可以用10 + (141 - 1) / 2 = 80求出。3)最后求具体落在哪一位上,可以用(141 - 1) % 2 = 0求出为第0位,即8。思路挺直观,可是要写出bug free的代码却不是那么容易。
代码:
class Solution {public: int findNthDigit(int n) { long digit = 1, ith = 1, base = 9; while(n > base * digit) { n -= base * digit; ++digit; ith += base; // the accumulated number base *= 10; } string s = to_string(ith + (n - 1)/digit); return s[(n - 1) % digit] - '0'; }};
阅读全文
0 0
- [leetcode] 400. Nth Digit 解题报告
- leetcode 400. Nth Digit解题报告
- [Leetcode] 400. Nth Digit 解题报告
- Leetcode 400. Nth Digit 第n个数字 解题报告
- 【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
- C#通过反射将DataRow转换成对应实体对象
- GoLang代码包的开发详细记录
- 安装破解idea 2017
- 点胶机对电子产品点胶注意事项?
- java中的内部类总结
- [Leetcode] 400. Nth Digit 解题报告
- Spring技术内幕——IOC部分摘录
- UVA 350
- Spark 之 RDD、DataFrame和DataSet的区别是什么
- Sass预处理语言
- mac终端 常用命令 总结
- angularjs学习总结 详细教程
- Data Binding does not support Jack builds yet
- 【机器学习】Andrew Ng——01概述