hdu1597(二分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yu121380/article/details/84571203

find the nth digit

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15968    Accepted Submission(s): 5042

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

HDU 2007-Spring Programming Contest - Warm Up (1)

解析:记录前i个有总的有多少个数,二分查找大于等于n的位置的i,则答案就是(n-f[i-1])%9;

为什么可以二分呢?因为2^32也就42亿多,而1叫到1e5就有50亿,说明可以二分

#include<bits/stdc++.h>
using namespace std;

#define e exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define mem(a,b) memset(a,b,sizeof(a))
int gcd(int a,int b){return b?gcd(b,a%b):a;}

const int maxn=1e5+5;
ll f[maxn];
void init()
{
	f[0]=0;
	for(ll i=1; i<maxn; i++)
	{
		f[i]=f[i-1]+i;
	}
}
int main()
{
	init();
	int T;scanf("%d",&T);
	while(T--)
	{
		ll n;scanf("%lld",&n);
		int x,l=1,r=1e5,mid=(l+r)/2;
		while(r-l>1)
		{
			if(f[mid]>n)r=mid;
			else l=mid;
			mid=(l+r)/2;
		}
		if(n>f[l])x=r;
		else x=l;
		printf("%d\n",(n-f[x-1])%9?(n-f[x-1])%9:9);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yu121380/article/details/84571203
今日推荐