以数学方式添加两个字符串?

OPJ*_*OPJ 3 c++ string int converter

我正在寻找论坛,我仍然找不到我的问题的答案.我有两个字符串,它们只是一个数字数组.例如(我只选择随机数

    string input1="12345678909876543212";
    string input2="12345";
Run Code Online (Sandbox Code Playgroud)

我想将这两个字符串加在一起,但就像整数一样.我的目标是创建一个类,我可以添加比(long long int)更大的数字,因此它可以超过最大的long long int变量.

所以我没有问题地发现了字符串,现在就在那里

  input1="21234567890987654321" 
  input2="54321"
Run Code Online (Sandbox Code Playgroud)

然后我尝试添加,假设input1 [0] + input2 [0](2 + 5)到一个新字符串让我们称之为newString [0],其中它将等于(7); 但我找不到一个好方法来暂时转换字符串中的当前数字,以便我可以将其添加到新字符串?有谁可以帮忙.我厌倦了atoi,stof,stod.他们似乎根本不适合我.任何方式我都可以使这个功能工作.我不关心上课,我只是想找到一种方法来数学地添加这两个字符串,但仍然保持newString的字符串格式.谢谢你能为我解决这个问题的人

P0W*_*P0W 5

好吧,假设您唯一的问题是逻辑,而不是类设计,我想出了这个逻辑

  • 用0填充输入,检查长度,匹配长度
  • 添加像正常添加,跟踪携带
  • 最后从结果中删除前导零

因此std::transform在反向迭代器上使用lambda函数: -

char carry = 0;

std::transform(input1.rbegin(),input1.rend(),input2.rbegin(),
              result.rbegin(),[&carry]( char x,  char y){
    char z = (x-'0')+(y-'0') + carry;
    if (z > 9)
    {
        carry = 1;
        z -= 10;
    }
    else
    {
        carry = 0;
    }
    return z + '0';
});

//And finally the last carry
result[0] = carry + '0';

//Remove the leading zero
n = result.find_first_not_of("0");
if (n != string::npos)
{
    result = result.substr(n);
}
Run Code Online (Sandbox Code Playgroud)

看到这里

编辑 "你能评论你在这里做什么"

                +--------+--------------+------------+-------> Reverse Iterator
                |        |              |            |
std::transform( | input1.rbegin(), input1.rend(),input2.rbegin(),
               result.rbegin(), [&carry]( char x,  char y){
               //This starts a lambda function
    char z = (x-'0')+(y-'0') + carry; // x,y have ASCII value of each digit
    // Substracr ASCII of 0 i.e. 48 to get the "original" number
    // Add them up
    if (z > 9) //If result greater than 9, you have a carry
    {
        carry = 1; // store carry for proceeding sums
        z -= 10; // Obviously 
    }
    else
    {
        carry = 0; //Else no carry was generated
    }
    return z + '0'; // Now you have "correct" number, make it a char, add 48
});
Run Code Online (Sandbox Code Playgroud)

std::transform在标题中出现<algorithm>,请参阅ideone发布的链接.