我和我的朋友都是网络编程专业的应届毕业生。为了好玩,我们决定研究随机 C++ 编码挑战,并且几乎完成了以下挑战,但它并未通过所有测试用例。我觉得我们已经很接近了,但可能有一个简单的错误需要纠正。任何帮助将不胜感激。
基本上,我们正在寻找最小和最大范围内尾随 9 最多的最大数字。任何范围内的最小数字为 0,最大为 3,000,000,000,因此我们使用 size_t。我们的测试用例:
情况 1:最小值 = 460,最大值 = 680,答案 = 599
情况 2:最小值 = 18696,最大值 = 18702,答案 = 18699
情况 3:最小值 = 1255,最大值 = 2999,答案 = 2999
我们最后一个(案例 3)工作得很好,但其他的没有通过。
#include<stdio.h>
#include<cmath>
#include<string>
int main()
{
size_t min = 460;
size_t max = 680;
size_t answer= max;
size_t tempAnswer = max;
size_t tempMax = max; // temporary placeholder to not modify max
size_t lastDigit = 0;
size_t tempLook = 0;
int count = 0;
// following variable gets the length of number (ex: 3000 = 3) if we add 1 to function call we get the real length, but we dont need the first digit.
int sizeOfMax = static_cast<int>(std::floor(std::log10(max)));
for (int i = 0; i < sizeOfMax; i++)
{
lastDigit = tempMax % 10; // looks at last digit in max
if (lastDigit == 9)
{
count++;
tempMax = tempMax / 10;
}
else {
for (int j = count; j > 0; j--)
{
tempMax *= 10;
tempLook = max % 10;
tempMax += tempLook;
}
if (count != sizeOfMax - count)
{
count = 0;
tempMax -= 1;
tempAnswer = tempMax;
i = -1;
}
}
if (answer < min)
{
answer = max;
}
else {
answer = tempAnswer;
}
}
printf("%zi", answer);
return 0;
}
再次,任何帮助将不胜感激。如果我需要用更多信息更新我的帖子,一旦我知道需要在帖子中添加哪些信息,我就会这样做。如果提供有关纠正错误的信息,我们也将不胜感激,以便我们能够理解原因。再次感谢!
如果最后一位数字不是 9,我尝试稍微修改上面的代码,但它会严重影响我的答案。
我也在 stackOverflow 上搜索了类似的问题/答案,但没有结果。
我不明白。您对案例 1 和案例 2 的回答对我来说似乎是正确的。当你说“带有最多尾随 9 的最大数字”时,什么优先,是更多的 9 还是更大的数字?例如,199 应该打败 219 吗?它有更多的尾随 9,但并不更高。
另外,我必须说实话,对于当前的问题来说,您的代码似乎过于复杂。我不会使用
tempMax
、tempAnswer
和 count
,而是简化代码,当您发现尾随 9 比当前 answer
多的数字时直接更新 answer
。
我知道这并不能直接解决您的问题,但我想提供一种替代方案,因为我个人认为您的代码有一些更大的问题,我什至无法开始调试它。此代码迭代从最小值到最大值范围内的每个数字。对于每个数字,它会检查最后一位数字是否不是 9。如果不是,它会检查它有多少个尾随 9。如果它至少有一个尾随 9 并且所有其他数字均为 0,则会相应更新答案:
#include <iostream>
size_t highestNumberWithTrailing9s(size_t min, size_t max) {
size_t answer = max;
for (size_t i = min; i <= max; ++i) {
if (i % 10 != 9) {
size_t trailing9s = 0;
size_t temp = i;
while (temp % 10 == 9) {
++trailing9s;
temp /= 10;
}
if (trailing9s > 0 && temp == 0) {
answer = i;
}
}
}
return answer;
}
int main() {
// Test cases
std::cout << highestNumberWithTrailing9s(460, 680) << std::endl; // Output: 599
std::cout << highestNumberWithTrailing9s(18696, 18702) << std::endl; // Output: 18699
std::cout << highestNumberWithTrailing9s(1255, 2999) << std::endl; // Output: 2999
return 0;
}