c ++字符串(int)+字符串(int) [英] c++ string (int) + string (int)

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

问题描述

我有2个字符串,都只包含数字。这些数字大于 uint64_t 的最大值。

I have 2 strings, both contain only numbers. Those numbers are bigger than max of uint64_t.

如何仍然将这两个数字相加,然后将结果转换为字符串?

How can I still add these 2 numbers and then convert the result to string?

推荐答案

嗯,您可以使用更大的数据类型(例如,处理大整数的库),也可以快速删除自己的数据类型。

Well, you can either use a bigger datatype (for example a library that deals with large integers), or you can quickly knock up your own.

我建议,如果这是一次性的,那么您将像在您上学的头几年学到的那样做长时间的加法。您可以直接对两个字符串进行操作,添加列,执行进位,然后构建另一个包含结果的字符串。您可以完成所有这些操作,而无需与二进制进行任何转换。

I would suggest that if this is a one off, you do long addition exactly like you would have learned to do in your first few years of school. You can operate directly on the two strings, add the columns, do the 'carry', and build another string containing the result. You can do all this without any conversion to or from binary.

此处。只是为了好玩,我为您提出了一个解决方案:

Here. Just for fun, I knocked up a solution for you:

string Add( const string& a, const string& b )
{
    // Reserve storage for the result.
    string result;
    result.reserve( 1 + std::max(a.size(), b.size()) );

    // Column positions and carry flag.
    int apos = a.size();
    int bpos = b.size();
    int carry = 0;

    // Add columns
    while( carry > 0 || apos > 0 || bpos > 0 )
    {
        if( apos > 0 ) carry += a[--apos] - '0';
        if( bpos > 0 ) carry += b[--bpos] - '0';
        result.push_back('0' + (carry%10));
        carry /= 10;
    }

    // The result string is backwards.  Reverse and return it.
    reverse( result.begin(), result.end() );
    return result;
}

请注意,为清楚起见,该代码甚至没有尝试处理错误。它也不会带来负面影响,但要解决这个问题并不难。

Note that, for clarity, this code doesn't even attempt to handle errors. It also doesn't do negatives, but it's not hard to fix that.

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

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