我有一个相当简单的想法。首先将两个整数 `n1`、`n2` 转换为 c-string `s1`、`s2`。然后如果 s1[0] = '-' (n1 为负) 改变 `s1[1] = 0`,否则 (n1>0) 改变 `s1[0] = 9`。对于 c-string `s2` 也是如此。最后比较哪个总和更大:`n1 + stoi(s2)` 或 `n2 + stoi(s1)` 以确定要选择的集合。
需要特别注意的是对于 >0 且以数字开头的整数`999...` 考虑到这种情况,我们使用 for 循环来更改不等于 `9` 的第一个数字。如果所有数字都是“9”,我们对整数不做任何事情。
#include <iostream>
#include <fstream>
#include <cstring>
int main()
{
int n1, n2, a, b;
char s1[32], s2[32];
while (1)
{
std::cout << "\n input n1 & n2 = ";
std::cin >> n1 >> n2;
itoa(n1, s1, 10);
itoa(n2, s2, 10);
if (s1[0] == '-') s1[1] = '0';
else for (int i=0; i<strlen(s1); i++) {
if (s1[i] = '9') continue;
else {s1[i] = '9'; break;}
if (s2[0] == '-') s2[1] = '0';
else for (int i=0; i<strlen(s2); i++) {
if (s2[i] = '9') continue;
else {s2[i] = '9'; break;}
a = n1 + std::stoi(s2);
b = n2 + std::stoi(s1);
if (a > b) std::cout << "two integers: " << n1 << ", " << s2 <<std::endl;
else std::cout << "two integers: " << s1 << ", " << n2 <<std::endl;
}
return 0;
}
一些测试集:
$ ./a.exe
input n1 & n2 = 12 78
two integers: 92, 78
input n1 & n2 = -45 90
two integers: -05, 90
input n1 & n2 = -34 -78
two integers: -34, -08
input n1 & n2 = 23 9999
two integers: 93, 9999