1019:Number Sequence

数学:

  1. 输入查找第n个位(1 ≤ n ≤ 2147483647),至少要有31268个组,才能使得数字序列达到有第2147483647位。
  2. 2147483647刚好是int的正整数最大极限值( ): 用int定义n。但是s[31268]存在超过2147483647的位数,因此要用unsigned 或long 去定义s[].
  3. 两个数学难点: (int)log10((double)i)+1, (i-1)/(int)pow((double)10,len-pos)%10。
  4. log()和pow()函数:传参的类型需要为double或float。
#include <iostream>
#include <cmath>
using namespace std;

const int len = 31269;
unsigned a[len];//第i组,数字序列的长度
unsigned s[len];//前i组,数字序列的长度

//打表,预先获取第2147483647个位的序列分组情况
void play_table() {
	a[1] = s[1] = 1;
	for (int i = 2; i < len; i++) {
		//log10(i)+1 表示第i组数字列的长度 比 第i-1组 长的位数
		a[i] = a[i - 1] + (int)log10((double)i) + 1;
		s[i] = s[i - 1] + a[i];
	}
	return;
}
//计算序列第n个位置上的数字
int compute(int n) {
	int i = 1;
	while (s[i] < n)
		i++;//确定第n个位置,出现在第i组
	int pos = n - s[i - 1];//pos为第n个位置 在 第i组中的下标值
	int tmp = 0;//第i组(n所在的组)的长度
	for (i = 1; tmp < pos; i++)
		tmp += (int)log10((double)i) + 1; 
	/*
	* 1.i-1,刚好等于第n位个置上的数
	* 2.len-pos就是第i组中pos位置后多余的数字位数
	* 要取出pos位上的数字,利用(i-1)/pow(10,len-pos),先删除pos后多余的数字
	* 再对剩下的数字取模,就可以得到pos
	*/
	return (i - 1) / (int)pow((double)10, tmp - pos) % 10;
}
int main() {
	play_table();
	int t,n;
	cin >> t;
	while (t--) {
		cin >> n;
		cout << compute(n) << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值