我好菜呀
数个数的题目脑子总是转不动
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
char findchar(long long n) {
stringstream ss;
string str;
char ch = 0;
int mi = 1;
long long seqCount = 0;
if (n < 0) { return -1; }
else {
if (n == 0) {
ch = 48;
return ch;
}
else {
while (true) {
//0 第0 个数; 1~9,第1~9个数;10~99,第 0+9 + 1 = 10 ~9*10*2 个数;100~999第 0+9+9*10*2 + 1 =191 ~0+9+9*10*2+9*100*3 个数;
if (seqCount + 9 * std::pow(10, mi - 1)* mi - n >= 0) {
break;//mi位数的共有个(0~9)数字位 9 *std::pow(10, mi-1) *mi
}
else {
seqCount += 9 * std::pow(10, mi - 1)* mi;
mi++;
}
}
}
//n=1,mi=1 ,seqCount=0,seqCount + 9 * std::pow(10, mi - 1)* mi = 9 > 1,跳出。
//n=9,````````````````````````````````````````````````````````````=9 =9 跳出
//n=10,``````````````````````````````````````````````````````````=9 不满足 >=10;
// mi=2, seqCount = 9`````````````````````````````````````````=189满足大于10跳出; //n=189,`````````````````````````````````````````````````````````=189满足大于10跳出;
long long number = std::pow(10, mi - 1) + (n - seqCount - 1) / mi;
long long left = (n - seqCount - 1) % mi;
ss << number;
ss >> str;
char ch = str.at(left);
return ch;
}
}
int main() {
for (int i = 0; i < 192; ++i) {
char ch = findchar(i);
cout << "第" << i << "个数字是" << ch << endl;
}
system("pause");
return 0;
}