您的位置:首页 > 其它

400. Nth Digit (leetcode) 。。。

2016-10-03 12:00 316 查看
题目的地址

https://leetcode.com/problems/nth-digit/

题目描述

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.


ac代码:(待优化。。。)

模拟找数的过程,先找到是几位数,再找打实际的数和响应的位置,最后再求出相应的数

class Solution {
public:
int findNthDigit(int n) {

if (n <= 9)
return n;

int size = 10;
vector<int> qsize(size,0);
vector<int> qcount(size,0);
vector<int> m(size,0);

qsize[1] = 9;
qcount[1] = 9;
m[1] = 9; // 最大的i位数???

for (int i = 2; i < size; i++)
{
qsize[i] = qsize[i - 1] * 10;
qcount[i] = qcount[i-1] + qsize[i]*i;
m[i] = m[i - 1] * 10 + 9;
}
qcount[9] = 0x7fffffff;

int index = 1;
while (index < size && qcount[index] < n)
{
index++;
}

// 说明查找的数是一个 有index位的数
int no = (n - qcount[index - 1]) / index;
int yushu = (n - qcount[index - 1]) % index;
if (yushu != 0)
{
no += 1;
}

int realno = m[index - 1] + no;
int weizhu = n - (no - 1) * index - qcount[index - 1]; // 从左到右 第weizhu位置
weizhu = index - weizhu;

for (int j = 0; j < weizhu; j++)
realno = realno / 10;

return realno % 10;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: