添加整数字符串 [英] Adding strings of integers

查看:99
本文介绍了添加整数字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为一个更大的项目编写一个算法,它将取两个字符串,这两个字符串都是大整数(为了这个演示,仅使用10个数字),并将它们添加在一起以产生最终的字符串,两个原始字符串的和。我意识到从一开始就有可能更好的方法,但我应该专门使用大整数的字符串,而不是一个长整数。

I'm trying to write an algorithm for a larger project that will take two strings which are both large integers (only using 10 digit numbers for the sake of this demo) and add them together to produce a final string that accurately represents the sum of the two original strings. I realize there are potentially better ways to have gone about this from the beginning but I am supposed to specifically use strings of large integers as opposed to a long integer.

我的想法是取两个原始字符串,颠倒他们的位置,十位置等所有排队正确添加。然后一次一个位置,将字符串从单个整数转换为单个整数,并将它们添加在一起,然后使用该和作为位置,否则为最终字符串,一旦完成也将反转回正确的字符顺序。

My thinking was to take the two original strings, reverse them so their ones position, tens position, and so on all line up properly for adding. Then one position at a time, convert the characters from the strings to single integers and add them together and then use that sum as the ones position or otherwise for the final string, which once completed will also be reversed back to the correct order of characters.

在我遇到麻烦时,我认为正在准备事件,其中来自字符串中相应位置的两个整数的和大于9 ,然后我会把一些剩余的继续到下一个位置。例如,如果我有7和5在我的位置,将添加到12,所以我会保持2,并添加1到十位置,一旦它环绕为十位置操作。

Where I'm running into trouble I think is in preparing for the event in which the two integers from the corresponding positions in their strings add to a sum greater than 9, and I would then have carry over some remainder to the next position. For example, if I had 7 and 5 in my ones positions that would add to 12, so I would keep the 2 and add 1 to the tens position once it looped back around for the tens position operation.

我没有得到任何准确的结果,花了大量的时间绊倒自己试图纠正我的算法,我不知道我需要做什么来解决这个问题。

I'm not getting results that are in any way accurate and after spending a large amount of time stumbling over myself trying to rectify my algorithm, I am not sure what I need to do to fix this.

希望我的预期流程清楚,有人能够指出正确的方向或纠正我在计划中可能遇到的一些错误。

Hopefully my intended process is clear and someone will be able to point me in the right direction or correct some mistake I may have in my program.

提前感谢。

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
    string str1 = "1234567890", str2 = "2345678901"; //Two original strings of large integers
    string rev_str1, rev_str2;
    int int1 = 0, int2 = 0;
    string final; //Final product string, sum of two original strings
    int temp_int = 0, buffer_int, remainder = 0;
    string temp_str = "", buffer_str;
    char buffer[100] = {0};

    cout << "str1 = " << str1 << endl;
    cout << endl;
    cout << "str2 = " << str2 << endl;
    cout << endl;

    rev_str1 = string(str1.rbegin(), str1.rend());
    rev_str2 = string(str2.rbegin(), str2.rend());

    for (int i = 0; i < 10; i++)
    {
        buffer_str = rev_str1.at(i);
        int1 = atoi(buffer_str.c_str());
        buffer_str = rev_str2.at(i);
        int2 = atoi(buffer_str.c_str());
        buffer_int += (int1 + int2 + remainder);
        remainder = 0;

        while (buffer_int > 9)
        {
            buffer_int -= 10;
            remainder += 10;
        }

        temp_str = itoa(buffer_int, buffer, 10);
        final += temp_str;
    }

    final = string(final.rbegin(), final.rend());

    cout << "final = " << final << endl;
    cout << endl;
}


推荐答案

。它只是两个summands;如果你有更多,你必须适应一些东西,特别是进位,然后可以大于19,以及分配结果字符串的方式:

Here's what I came up with. It is just for two summands; if you have more, you'll have to adapt things a bit, in particular with the carry, which can then be larger than 19, and the way the result string is allocated:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    // Two original strings of large integers
    string str1 = "1234567890",
           str2 = "2345678901234";

    // Zero-padd str1 and str2 to the same length
    size_t n = max(str1.size(), str2.size());
    if (n > str1.size())
        str1 = string(n-str1.size(), '0') + str1;
    if (n > str2.size())
        str2 = string(n-str2.size(), '0') + str2;

    // Final product string, sum of two original strings.
    // The sum of two integers has at most one digit more, for more inputs make
    // below reverse_iterator a back_insert_iterator, then reverse the result
    // and skip the removal of the padding.
    string final(n+1, '0');

    // The carry
    char carry = 0;

    // Iterators
    string::const_reverse_iterator s1 = str1.rbegin(), e = str1.rend(),
                                   s2 = str2.rbegin();
    string::reverse_iterator f = final.rbegin();

    // Conversion
    for (; s1 != e; ++s1, ++s2, ++f)
    {
        // Bracketing to avoid overflow
        char tmp = (*s1-'0')+(*s2-'0') + carry;
        if (tmp > 9)
        {
            carry = 1;
            tmp -= 10;
        }
        else
        {
            carry = 0;
        }
        *f = tmp + '0';
    }
    final[0] = carry + '0';

    // Remove leading zeros from result
    n = final.find_first_not_of("0");
    if (n != string::npos)
    {
        final = final.substr(n);
    }

    cout << "str1 = " << str1 << endl
         << "str2 = " << str2 << endl
         << "final = " << final << endl;
}

这篇关于添加整数字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆