Algorithm
problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1647
A single positive integer i is given. Write a program to find the digit located in the position i in the sequence of number groups S1S2 . . . Sk. Each group Sk consists of a sequence of positive integer numbers ranging from 1 to k, written one after another. For example, the first 80 digits of the sequence are as follows: 11212312341234512345612345671234567812345678912345678910123456789101112345678910 Input The first line of the input file contains a single integer t (1 ≤ t ≤ 25), the number of test cases, followed by one line for each test case. The line for a test case contains the single integer i (1 ≤ i ≤ 2147483647) Output There should be one output line per test case containing the digit located in the position i.
Sample Input 2 8 3
Sample Output 2 2
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <bits/stdc++.h>
using namespace std;
int main()
{
string sequence = ""; // store single sequence
int totalLength=0; // length from 1 to n
vector < long long> lens(1,0); // cumulative length of concat seq
for(int i=1;i < 35000;i++){
int length = (int)log10(i)+1;
totalLength += length;
sequence += to_string(i);
lens.push_back(totalLength+lens.back());
}
int t,v;
cin >> t;
while(t--){
cin >> v;
int low = 0, high = 34999;
// bisect right to find next smaller sequence
while(low < high){
int mid = (low+high)/2+1;
if(lens[mid] >= v) high = mid-1;
else low = mid;
}
// n-th digit in sequence
printf("%c\n", sequence[v-lens[high]-1]);
}
}
Copy The Code &
Try With Live Editor
Input
8
3
Output
2
Demonstration
UVA Online Judge solution - 10706-Number Sequence - UVA Online Judge solution in C,C++,java