【发布时间】:2021-08-29 08:25:20
【问题描述】:
我有一个无限长的字符串“12345678910111213141516171819202122232425...”,它是每个自然数的升序连接。我想在字符串中找到第 k 个字符。但是,尽管逻辑正确,但我的程序却给了我不正确的输出。我怀疑某处存在实现错误
#include <iostream>
int main() {
using std::cin;
using std::cout;
std::ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while (T--) {
int64_t k;
cin >> k;
int64_t aux = 9;
int digit = 1;
while (k > aux * digit) {
k -= aux * digit;
aux *= 10;
digit++;
}
int64_t ans = 1;
for (int i = 0; i < digit - 1; i++) {
ans *= 10;
}
ans += (k - 1) / digit - 1;
k -= (k - 1) / digit * digit;
int64_t helper = 1;
for (int i = 0; i < digit - k; i++) {
helper *= 10;
}
cout << ans / helper % 10 << '\n';
}
return 0;
}
输入:
3
7
19
12
预期输出:
7
4
1
我的输出
6
3
1
【问题讨论】:
-
嗯,你尝试调试你的程序了吗?
-
考虑在 Code Review 上发帖:codereview.stackexchange.com
-
@Quimby I. 没有。我没学过。那还没有..
-
@carcinogenicgame 很公平,但这是学习的基本技能。见how to debug small programs。取决于您使用的 IDE,但都可以做基本的事情。