POJ1019 Number Sequence

题目链接

题解

二分出答案要求的数字出现在$1234\cdots n$里面的$n$的值,然后计算具体是这一串数里面的哪一个数的哪一位。后面这个子问题在leetcode 400上有。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cctype>
using namespace std;
int s[10], cnt;
unsigned int get(int t){
int pst = 0, u = 9, res = 0, a1 = 0;
for(int i = 1; ; ++i){//d = i
a1 += i;
int terms = min(u, t) - pst;
res += terms * a1 + (terms * (terms - 1) / 2) * i;
if(t <= u)
break;
a1 += i * (u - pst - 1);
pst = u, u = 10 * u + 9;
}
return res;
}
int solve(unsigned int n){
int l = 1, r = 35000;
while(l < r){
int mid = (l + r) >> 1;
if(get(mid) >= n)
r = mid;
else
l = mid + 1;
}
int gap = n - get(r - 1);
if(gap <= 9)
return gap;
int i = 1, u = 9;
while(gap > u){
gap += u, u = u * 10 + 9, ++i;
if(gap <= i * u){
int res = (gap + i - 1) / i;
cnt = 0;
while(res)
s[cnt++] = res % 10, res /= 10;
return s[cnt - 1 - ((gap + i - 1) % i)];
}
}
}
int main(){
int T;
unsigned int n;
scanf("%d", &T);
while(T--){
scanf("%u", &n);
printf("%d\n", solve(n));
}
return 0;
}