400. Nth Digit
2016-09-21 12:52
92 查看
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.
这题基本思路就是观察发现,一位数从1-9,9个,两位数从10-99,90个,三位数从100-999,900个,以此类推,我们要做的就是将n定位在一个几位数的区间里,然后算一下和这个区间的头或者尾的差距从而定位具体的数字。思路很简单,可能会有的错误就是虽然n是int,但我们算的数字总和可能会溢出,所以这里使用long long int来做。
代码如下:
int findNthDigit(int n) { long long int st = 9; long long int bits = 1; long long int sum = 0; while (true) { sum += (st * bits); if (sum >= n) break; st = st * 10; bits++; } int pos = pow(10.0, double(bits)) - 1 - (sum - n)/(bits); int rem = sum - n - bits * ((sum - n) / bits); int temp = pow(10.0, double(rem)); return (pos / temp) % 10; }
注意c++里的pow求次方的函数操作类型是double。
相关文章推荐
- [leetcode] 400. Nth Digit 解题报告
- leetcode 400. Nth Digit
- 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-400. Nth Digit
- 400. Nth Digit
- [leetcode: Python]400. Nth Digit
- [Leetcode] 400. Nth Digit 解题报告
- LeetCode400. 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