程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> POJ1019:Number Sequence

POJ1019:Number Sequence

編輯:C++入門知識

POJ1019:Number Sequence


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.

Sample Input

2
8
3

Sample Output

2
2

Source

Tehran 2002, First Iran Nationwide Internet Programming Contest

題目大意就是給你這一串數字11212312341234512345612345671234567812345678912345678910123456789101112345678910……(未列完)

要我們求出第n個數是多少(從左到右看),例如第2個是1,第三個是2,第八個是2;

如果仔細觀察這一串數字,可以發現他可以還分為很多小串,假設第i小串是123……i,假設第i小串所占的空間是a[i],則通過對比a[i]與a[i+1]發現,

第i+1串只比第i串多一個數,即i+1,故他們所占的空間差就是第i+1所占的空間。

對任意一個數所占的空間很好求,即 (int)log10(k)+1;

然後就可以求出每一個串的起始位置,通過與n比較就可以確定n出現在那一個串裡,最後在求出n在這個串裡的相對位置,就可以求出該題的解


#include 
#include 
#include 
#include 
#include 
#include
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define ls 2*i
#define rs 2*i+1
#define up(i,x,y) for(i=x;i<=y;i++)
#define down(i,x,y) for(i=x;i>=y;i--)
#define mem(a,x) memset(a,x,sizeof(a))
#define w(a) while(a)
#define LL long long
const double pi = acos(-1.0);
#define N 32000
#define mod 19999997
#define INF 0x3f3f3f3f
#define exp 1e-8
int a[40000],num[1000000],l;
LL s[40000];
int main()
{
    int t,n,i,j,k;
    a[0] = 0;
    a[1] = 1;
    up(i,2,N)
    {
        a[i]=a[i-1]+(int)log10(1.0*i)+1;//加上每個數字所占得位數,得到第i個串的長度
    }
    s[0] = 1;
    up(i,1,N)//計算得到第i個串起始的坐標
    {
        s[i]=s[i-1]+a[i-1];
    }
    l = 1;
    up(i,1,N)//計算出最長的那個串是怎樣的
    {
        int bit[50];
        t = i;
        int len = 0;
        w(t)
        {
            int r = t%10;
            bit[len++] = r;
            t/=10;
        }
        w(len--)
        {
            num[l++] = bit[len];
        }
    }
    scanf("%d",&t);
    w(t--)
    {
        scanf("%d",&n);
        up(i,1,N)
        {
            if(s[i]>=n)
                break;
        }
        if(s[i]==n)//是一個串的開頭
            printf("1\n");
        else//找到位置
            printf("%d\n",num[n-s[i-1]+1]);
    }

    return 0;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved