c++ - 根据数字确定大数二
问题描述
我正在尝试解决这个简单的问题。我开发了这样的算法,它似乎适用于我能想到的每一个可能的输入。以下是我大学在线法官的确切问题陈述。
任务:
给你两个自然数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并按字典顺序进行比较:
#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;
}
推荐阅读
- vba - 节标题 Range.Text 返回空字符串而不是实际文本
- php - imgur 通过 api 删除图像
- oracle11g - SQL 错误:ORA-00904: : 第 4 行中的标识符无效
- javascript - 如何在 google-maps-react 中获取所有标记
- java - 如何在java中获取和打印字符串
- java - 如何使用 servlet 更新 JSP 中的值?
- javascript - “无法读取未定义的属性‘类型’”在 redux 存储中用于外部包中定义的操作
- javascript - Blogger 的 Photoswipe 集成
- javascript - 限制帐单地址列表
- wordpress - wordpress wp-content/uploads 文件夹 301 通过 cloudfrond CDN 通过 .htaccess 问题重定向到 S3 存储桶