您的位置:首页 > 其它

leetcode 400. Nth Digit

2016-10-24 14:44 295 查看
解题思路:

如果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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: