Number Sequence(POJ--1019

Description

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 ≤ 10), 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.
题意:如题目所描述,给你一串数112123123412345.............,t组输入,每组输入一个n,求在那串数中第n个数字是多少。【PS:是数字而不是数,假如那一串数是12345678910,那么第10位数字是1而不是10】。
思路:通过观察可以发现这一串数可以分为若干部分小串即模拟分组,把1看作第1组,12看作第2组,123看作第3组...那么第i组就是存放数字序列为[1,i]的正整数,但第i组的长度不一定是i。因为查找的位数n的范围是1~2147483647,那么数组至少要开到31268才能使数字序列达到有第2147483647位。
注意:2147483647正好是int的最大极限值,所以对于n用int定义就足矣,但是s[31268]存在超过2147483647的位数,所以数组s要用unsigned或long之类的去定义。

技巧:

log()和pow()函数的使用:

两个都是重载函数,函数原型分别为

double log(double)

float log(float)

double pow(double , double)

float pow(float ,float)

所以当传参的类型不是double或float时,必须强制转换为其中一种类型,否则编译出错。一般建议用double

Sample Input
2
8
3

Sample Output

2
2

#include <cstdio>
#include <cmath>
#include <algorithm>
#define MAX 32000
using namespace std;
char ch[MAX*10];          //存储最长的数字串
long long int s[MAX+10]= {0,1},len[MAX+10]= {0,1};   //s[i]存储第i组第一个数的编号,len[i]记录第i组的长度,在定义数组时如果直接赋值则其值从数组的第0位开始赋值
int main()
{
    char *p=ch+1;             //指针指向数组的第一位
    for(int i=1; i<=MAX; i++)
    {
        sprintf(p,"%d",i);        //将数字直接输出到字符串ch中
        p+=(int)log10(i)+1;     //p向后移输入数字的位数,(int)log10(i)+1即数字的位数
    }
    *p=0;
    for(int i=2; i<=MAX; i++)     //递推获得数串长度数组
        len[i]=len[i-1]+(int)log10(i)+1;
    for(int i=2; i<=MAX; i++)    //递推获得数组s[]
        s[i]=s[i-1]+len[i-1];
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int x=lower_bound(s+1,s+1+MAX,n)-s;  //用二分查找寻找n所在的组,lower_bound函数返回的是在数组s中最接近n且大于等于n的那个数的下标
        if(s[x]==n)
            printf("1\n");
        else
            printf("%c\n",ch[n-s[x-1]+1]);
    }
    return 0;
}<strong>
</strong>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值