首页 > 解决方案 > 根据数字确定大数二

问题描述

我正在尝试解决这个简单的问题。我开发了这样的算法,它似乎适用于我能想到的每一个可能的输入。以下是我大学在线法官的确切问题陈述。

任务:
给你两个自然数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。我错过了什么?

标签: c++

解决方案


您可以将数字读取为std::strings并按字典顺序进行比较:

#include <iostream>
#include <string>

int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    std::string number1;
    std::string number2; 
    std::cin >> number1 >> number2;
    std::cout << std::max(number1, number2) << '\n';

    return 0;
}

推荐阅读