题解 | #高精度整数加法#

高精度整数加法

https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

#include <iostream>
using namespace std;
#include <string>

void caculate(string longNum, string shortNum)
{

    string s2(longNum.size(), '0');
    string s3(longNum.size(), '0');
    // 扩展短的数组
    for (int i = shortNum.size() - 1, j = 1; i >= 0; i--, j++)
    {
        s2[s2.size() - j] = shortNum[i];
    }

    int temp = 0;
    for (int i = longNum.size() - 1; i >= 0; i--)
    {
        int a = longNum[i] - '0';
        int b = s2[i] - '0';
        int c = a + b + temp;
        temp = 0;
        if(c<10){
            s3[i] = c + '0';
        }
        else{
            s3[i] = c - 10 + '0';
            temp = c/10;
        }
    }
    if(temp != 0){
        cout << temp;
    }
    cout << s3;
}

int main()
{
    string num1;
    string num2;
    bool flag = 0;
    getline(cin, num1);
    getline(cin, num2);
    if (num1.size() >= num2.size())
    {
        caculate(num1, num2);
    }
    else
    {
        caculate(num2, num1);
    }
}

设置进位缓存和最后进位的检查即可

有个小技巧,将短的那个字符串前面对齐0,可以简化计算的代码

华为机试刷题记录 文章被收录于专栏

记录一下手打代码的解题思路方便复习

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务