Number Sequence
Time Limit: 1000MS Memory Limit: 10000K
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:
11212312341234512345612345671234567812345678912345678910123456789101112345678910Input
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
3Sample Output
2
2
我的解法思路是没问题的,就是边界问题花了不少时间,o(╥﹏╥)o
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
//寻找该位置在该一列中所在的位置
int calcRealIndex(int startPos, int addCnt, int sIns, int ins, double index) {
if (ins == sIns) {
return index;
}
//2分法查找
double banNum = (ins - sIns) / 2 + sIns;
long long tempCnt1 = 2 * startPos;
long long tempCnt2 = addCnt * (banNum + sIns);
long long tempCnt3 = tempCnt1 + tempCnt2;
long long tempCnt = tempCnt3 * (1.0 * banNum / 2);
if (tempCnt >= index) {
return calcRealIndex(startPos, addCnt, 1, banNum, index);
}
else {
return calcRealIndex(startPos + banNum * addCnt, addCnt, 1, ins - banNum, index - tempCnt);
}
}
//通过该列中的位置寻找真正的值
int calcRealNum(int index) {
for (int i = 1; ; i++) {
int ins = pow(10.0, i) - pow(10.0, i - 1);
if (index <= ins * i) {
int realNum = ((index - 1) / i) + pow(10.0, i - 1);
char s[20];
sprintf_s(s, "%d", realNum);
return s[(index - 1) % i] - '0';
}
index -= ins * i;
}
}
int main() {
int t;
cin >> t;
for (int _t = 0; _t < t; _t++) {
int i;
cin >> i;
long long cnt = 0;
int startPos = 0;
int addCnt = 1;
for (; cnt <= 2147483647; addCnt++) {
int ins = pow(10.0, addCnt) - pow(10.0, addCnt - 1);
long long tempAddCnt = (startPos + addCnt + startPos + addCnt * ins) * (1.0 * ins / 2);
if (cnt + tempAddCnt >=i) {
int realIndex = calcRealIndex(startPos, addCnt, 1, ins, i - cnt);
int max = cnt + tempAddCnt;
cout << calcRealNum(realIndex) << endl;
break;
}
//往上就越界了,直接写死结束
else if (cnt + tempAddCnt >= 189414495) {
cnt += tempAddCnt;
startPos += ins * addCnt;
addCnt++;
int realIndex = calcRealIndex(startPos, addCnt, 1, 50000, i - cnt);
cout << calcRealNum(realIndex) << endl;
break;
}
cnt += tempAddCnt;
startPos += ins * addCnt;
}
}
return 0;
}