leetcode 400. Nth Digit
2016-10-24 14:44
295 查看
解题思路:
如果n<9, 返回n
如果n<9 + 2 * 90, 说明是某个两位数中的一位
如果n<9 + 2 * 90 + 3 * 900,说明是某个三位数中的一位
…
首先判断第n个数是属于几位数,然后判断属于该数的第几位
注意 表达式的结果可能溢出,导致结果错误
原题目:
AC解,C++代码,菜鸟一个,请大家多多指正
如果n<9, 返回n
如果n<9 + 2 * 90, 说明是某个两位数中的一位
如果n<9 + 2 * 90 + 3 * 900,说明是某个三位数中的一位
…
首先判断第n个数是属于几位数,然后判断属于该数的第几位
注意 表达式的结果可能溢出,导致结果错误
原题目:
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 < 2E31). 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.
AC解,C++代码,菜鸟一个,请大家多多指正
class Solution { public: int tenPower(int n) { int ret = 1; while (n > 0) { ret *= 10; n--; } return ret; } int findNthDigit(int n) { int i = 0; while (true) { i++; if ((n - 1) / (i * 9) >= tenPower(i - 1)) { n -= i * 9 * tenPower(i - 1); } else { break; } } int num_pos = (n - 1) / i + tenPower(i - 1); int bit_pos = (n - 1) % i; return (num_pos / tenPower(i - 1 - bit_pos)) % 10; } };
相关文章推荐
- Leetcode 400. Nth Digit[easy]
- 【LeetCode】 400. Nth Digit
- leetcode 400. Nth Digit解题报告
- LeetCode 400. Nth Digit
- LeetCode - 400. Nth Digit
- LeetCode-400. Nth Digit
- 【C语言】 LeetCode 400. Nth Digit
- 【Leetcode】400. Nth Digit
- (Leetcode)400. Nth Digit
- LeetCode 400. Nth Digit
- LeetCode-400. Nth Digit
- leetcode_400. Nth Digit 查找自然数序列中的第n个数字
- Leetcode 400. Nth Digit (Easy) (cpp)
- leetcode 400. Nth Digit 从1到n第n位数字是什么 + 找规律
- LeetCode 400. Nth Digit
- LeetCode | 400. Nth Digit 数学原理题
- [Leetcode] 400. Nth Digit 解题报告
- [leetcode] 400. Nth Digit 解题报告
- LeetCode—400. Nth Digit
- LeetCode 400. Nth Digit