You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

大整数求和代码在特定测试用例下失败,请求技术排查

大整数求和算法BUG排查与修复

我实现了一个模拟手动计算逻辑的大整数求和算法,C++代码在多数场景下运行正常,但在测试用例9223372036854775808 + 486127654835486515383218192时失败,输出结果为+'2+-0+*.4058858552237994000。代码已经做了进位处理和不同位数数字相加的逻辑,但搞不懂这个测试用例的特殊之处,附上代码求助:

// Basic mechanism: 
//reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value 
// reverse the result.
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
#include <iostream>
#include <cstring>
using namespace std;

string strA;
string strB;
string ResStr = ""; // empty result string for storing the result 
int carry =0;
int  sum; //intermediary sum
int n1; //length of string 1
int n2; // length of string 2
int rem; // remainder

int main()
{
    cout << "enter" << endl;
    cin >> strA;
    cout << "enter" << endl; // I didn't know how to write this program to use argv[1] and argv[2] so this was my solution 
    cin >> strB;
  
    // turning the length of each string into an integer 
    int n1 = strA.length(), n2 = strB.length();
 
if (n1<n2){
    swap(strA,strB);
}//for this part I have no idea why this has to be the case but it only works if this statement is here 

    // Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
    reverse(strA.begin(), strA.end());
    reverse(strB.begin(), strB.end());
 
  
    for (int i=0; i<n2; i++)//start at 0, perform this operation until the amount of times reaches the value of n2
    {
        //get the sum of current digits 
        int sum = ((strA[i]-'0')+(strB[i]-'0')+carry);
        int quotient=(sum/10);
        int rem=(sum-10*quotient);
        ResStr+=(rem+'0'); //this gets the remainder and adds it to the next row

        // Calculate carry for next step. Thus works because carry is an integer type, so it will truncate the quotient to an integer, which is what we want
        carry = sum/10;
    }
 
    // Add the remaining digits of the larger number 
    for (int i=n2; i<n1; i++) //start at n1, perform this operation until the amount of times reaches the value of n1
    {
        int sum = ((strA[i]-'0')+carry);
        int quotient=(sum/10);
        int rem=(sum-10*quotient);
        ResStr+=(rem+'0');
        carry = sum/10;
    }
 
    // Add remaining carry over value
    if (carry)
        ResStr+=(carry+'0');
    // reverse the resulting string back, because we reversed it at the beginning 
    reverse(ResStr.begin(), ResStr.end());
    
    cout << "The result is " << ResStr << endl;
    return 0;
}

问题根源分析

  1. 全局变量与局部变量冲突:全局定义了n1、n2,但main里又重新定义同名局部变量。交换字符串后,后续循环实际使用未初始化的全局n1、n2(垃圾值),导致字符串越界访问,输出乱码。
  2. 交换字符串未同步长度:交换strA和strB后,未同步交换n1和n2,即使局部变量无冲突,后续循环的长度匹配也会出错。
  3. 缺失必要头文件:使用reverse函数但未包含<algorithm>头文件,属于未定义行为,不同编译器可能出现异常。

修复后的代码

// 模拟手动计算的大整数求和逻辑
// 反转字符串让低位对齐,逐位相加处理进位,最后反转结果得到正确顺序
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
{
    string strA, strB, ResStr = "";
    int carry = 0;
  
    cout << "enter" << endl;
    cin >> strA;
    cout << "enter" << endl;
    cin >> strB;
  
    int n1 = strA.length(), n2 = strB.length();
 
    // 确保strA是较长的字符串,方便后续统一处理
    if (n1 < n2) {
        swap(strA, strB);
        swap(n1, n2);
    }

    reverse(strA.begin(), strA.end());
    reverse(strB.begin(), strB.end());
 
    // 逐位相加两个字符串的共同长度部分
    for (int i = 0; i < n2; i++) {
        int sum = (strA[i] - '0') + (strB[i] - '0') + carry;
        int rem = sum % 10; // 取模直接得到当前位结果
        ResStr += (rem + '0');
        carry = sum / 10; // 计算进位
    }
 
    // 处理较长字符串剩余的高位部分
    for (int i = n2; i < n1; i++) {
        int sum = (strA[i] - '0') + carry;
        int rem = sum % 10;
        ResStr += (rem + '0');
        carry = sum / 10;
    }
 
    // 处理最后剩余的进位
    if (carry) {
        ResStr += (carry + '0');
    }
    // 反转结果得到正确顺序
    reverse(ResStr.begin(), ResStr.end());
    
    cout << "The result is " << ResStr << endl;
    return 0;
}

修复说明

  • 移除全局变量,所有变量放在main内,避免作用域冲突和未初始化问题。
  • 交换字符串后同步交换长度值,确保后续循环的长度匹配正确。
  • 添加<algorithm>头文件,保证reverse函数正常工作。
  • 用sum % 10简化余数计算,代码更简洁易读。

内容的提问来源于stack exchange,提问作者leialeia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:55:32