Number Sequence
Input: standard input
Output: standard output
Time Limit: 1 second
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 tok, 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 Output for Sample Input
2 8 3 | 2 2 |
解决方案:主要是通过二分查找解决。先得到一串最长的由1.......n位数组成的字符串。然后:
1-9:每增加一个数,在原来的基础上多一位
10-99:每增加一个数,在原来的基础上多两位。
100-999:每增加一个数,在原来的基础上多三位。
。。。。。
所以可以打个表:
可把整个串分成这样:
1
12
123
1234
12345
....
1234567891011
把这些串的的最后一个位置打个表。
最后二分查找即可以把其位置转成在一串最长的由1.......n位数组成的字符串的相应位置,输出相应字符。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#define MMAX 31270
#define NMAX 146000
using namespace std;
unsigned int n;
unsigned int a_list[MMAX];
void init(){
a_list[0]=0;
int c=10,x=1,sum=0;
for(int i=1;a_list[i-1]<=2147483650;i++)
{
if(i==c){
x++;
c*=10;
}///i的位数每增加一次,位置也就要加一次
sum+=x;
a_list[i]=a_list[i-1]+sum;
}
// cout<<sum<<endl;
}
int main(){
int t;
init();///打表
scanf("%d",&t);
while(t--){
scanf("%d",&n);
string str;
str.reserve(NMAX+10);
for(int i=1;str.length()<=NMAX;i++){
char temp[10];
sprintf(temp,"%d",i);
str+=temp;
}
//printf("%c",str[90]);
int mid,low=1,high=31268;
int s=-1;// cout<<high<<" "<<low<<" "<<mid<<endl;
while (low <= high)
{ //cout<<"sd";
int mid = (low + high) / 2;
if (n == a_list[mid])
{
s=a_list[mid-1];break;
}
else if (n < a_list[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}///二分查找
//printf("%d %d %d\n",low,mid,high);
//printf("%d %d\n",a_list[mid-1],a_list[mid]);
if(s!=-1){
printf("%c\n",str[n-s-1]);}
else{printf("%c\n",str[n-a_list[high]-1]);
}
}
return 0;}