Algorithm
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345…" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, …, the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer ki. Calculate the digit at the position ki of the sequence.
The first line of the input contains one integer q (1≤q≤500) — the number of queries.
The i-th of the following q lines contains one integer ki (1≤ki≤109) — the description of the corresponding query.
Print q lines. In the i-th line print one digit xi (0≤xi≤9) — the answer to the query i, i.e. xi should be equal to the element at the position ki of the sequence.
5 1 3 20 38 56
1 2 5 2 0
4 2132 506 999999999 1000000000
8 2 9 8
Answers on queries from the first example are described in the problem statement.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int const N = 1e6;
int q;
long long cm1[N];
long long cm2[N];
int get_digit(int n, int i) {
int nrev = 0;
while(n != 0) {
nrev *= 10;
nrev += (n % 10);
n /= 10;
}
int cnt = 0, cur = 0;
while(cnt != i) {
cur = nrev % 10;
nrev /= 10;
cnt += 1;
}
return cur;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
cm1[0] = cm2[0] = 0;
for(int i = 1; i < N; ++i)
cm1[i] = floor(log10(i)) + 1;
cm2[1] = 1;
for(int i = 2; i < N; ++i)
cm1[i] += cm1[i - 1], cm2[i] = cm1[i];
for(int i = 2; i < N; ++i)
cm2[i] += cm2[i - 1];
scanf("%d", &q);
for(int i = 0, tmp; i < q; ++i) {
scanf("%d", &tmp);
int idx = lower_bound(cm2 + 1, cm2 + N, tmp) - cm2;
tmp -= cm2[idx - 1];
idx = lower_bound(cm1 + 1, cm1 + N, tmp) - cm1;
printf("%d\n", get_digit(idx, tmp - cm1[idx - 1]));
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
1
3
20
38
56
Output
2
5
2
0
Demonstration
Codeforcess Solution E1. Numerical Sequence (easy version)-Solution in C, C++, Java, Python ,Codeforcess Solution