我正在尝试解决这个简单的问题。我开发了这样的算法,它似乎适用于我能想到的所有可能的输入。以下是我大学在线法官的确切问题陈述。
任务:您会得到两个自然的N数字。用数字比较它们并写出较大的数字。
输入:包含两个自然数,这些自然数不大于10 18。
输出:两个数字中较大的一个。
代码:
#include <iostream> // Problem 61, comparing two numbers by their digits.
#include <cmath>
//#include <climits>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
long long int n, k; cin >> n >> k;
long long int x = n, y = k;
if (n == 0) { cout << k; return 0; } //log(0) undefined
if (k == 0) { cout << n; return 0; }
long long int len_n = int(log10(n)) + 1, len_k = int(log10(k)) + 1;
if (len_n > len_k) { cout << n; }
else if (len_n < len_k) { cout << k; }
else {
long long int num_n, num_k, count_n = 0, count_k = 0;
for (long long int i = 0; i < len_n; i++) {
num_n = n % 10; num_k = k % 10;
count_n += num_n; count_k += num_k;
n /= 10; k /= 10;
}
if (count_n > count_k) { cout << x; }
else { cout << y; }
}
return 0;
}
问题在于,它在在线法官的测试案例4中失败。我想念什么?
您应该将数字读为std::strings。您可以使用std::accumulate
对数字求和#include <iostream>
#include <numeric>
#include <string>
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
std::string number1;
std::string number2;
std::cin >> number1 >> number2;
auto sum1 = std::accumulate(std::begin(number1), std::end(number1), 0, [](auto const &s, auto const &c){ return s+c-'0';});
auto sum2 = std::accumulate(std::begin(number2), std::end(number2), 0, [](auto const &s, auto const &c){ return s+c-'0';});
if (sum1 > sum2) std::cout << number1 << '\n';
else std::cout << number2 << '\n';
return 0;
}
如果问题的确是在两个自然数中找到更大的数字之和,则可以在您的内循环中创建一个辅助函数,但跳过log10
操作。只需检查您的值是否不为0:
inline unsigned sum_digits(unsigned long long x) {
unsigned result = 0;
while(x) { // loop for as long as it still carry a digit
result += static_cast<unsigned>(x % 10);
x /= 10;
}
return result;
}
这样比较会很容易。 if(sum_digits(n) < sum_digits(k)) ...