hdu 1597 数学题 find the nth digit

find the nth digit

                                                                                            题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1597
Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9141    Accepted Submission(s): 2614


Problem Description
假设:
S1 = 1
S2 = 12
S3 = 123
S4 = 1234
.........
S9 = 123456789
S10 = 1234567891
S11 = 12345678912
............
S18 = 123456789123456789
..................
现在我们把所有的串连接起来
S = 1121231234.......123456789123456789112345678912.........
那么你能告诉我在S串中的第N个数字是多少吗?
 

Input
输入首先是一个数字K,代表有K次询问。
接下来的K行每行有一个整数N(1 <= N < 2^31)。
 

Output
对于每个N,输出S中第N个对应的数字.
 

Sample Input
6 1 2 3 4 5 10
 

Sample Output
1 1 2 1 2 4
 

Author
8600
 

Source


先用一个数组a[i],表示拼接了i个串之后串s的长度

之后,对于任意的N,先用二分法找出长度为N时前面是由几个串拼接成的,这样再取下模,答案就出来了

代码:

#include <iostream>
using namespace std;
const int maxn=66100;
#define INT_MAX 2147483600
int a[maxn];int k;
int init()
{
    int i;
    a[0]=0;
    for( i=1;;i++)
    {
        if(a[i-1]>=INT_MAX-i)//如果i-1时 总数超过intmax break
            break;
        a[i]=a[i-1]+i;
    }
    a[i]=INT_MAX;
    k=i+1;// 标记最后的一个串的位置
}
int bin_search(int key)//二分法
{
    int head=1;
    int tail=k;
    while(head<=tail)
    {
        int mid=(head+tail)/2;
        if(a[mid]<=key&&a[mid+1]>key)
            return mid; 
        else if(a[mid]>key)
        {
            tail=mid-1;
        }
        else
            head=mid+1;
    }
    return k;
}

int main()
{
    int k;
    cin>>k;
    init();
    while(k--)
    {
        int n;
        cin>>n;
        int t=bin_search(n);
        int ans=n-a[t];
        if(ans==0)
        {
            ans=a[t]-a[t-1];
        }
        if(ans%9==0)
            cout<<"9\n";
        else
            cout<<ans%9<<endl;
    }
    return 0;
}
对于看不懂的地方 对照几组样例应该就能看懂啦

学习了http://www.cnblogs.com/nanke/archive/2011/08/02/2125248.html的代码 思路。


posted @ 2015-04-15 22:15  编程菌  阅读(195)  评论(0编辑  收藏  举报