Multiply Strings

本文详细介绍了如何使用C++实现两个任意大小的非负整数字符串相乘和相加的功能,通过内部函数实现逐位运算并处理进位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

 

class Solution {
public:
    string addTwoString(string nums1, string nums2) {

        int n1 = nums1.size();
        int n2 = nums2.size();

        if (n1 < n2)
            return addTwoString(nums2, nums1);

        int minlen = n2;
        int maxlen = n1;
        string result;
        int carry = 0;
        for (int i = 0; i < minlen; i++) {
            int sum = nums1[--n1] - '0' + nums2[--n2] - '0' + carry;
            carry = sum / 10;
            int a = sum % 10;
            result.push_back(a + '0');
        }
        for (int i = minlen; i < maxlen; i++) {
            int sum = nums1[--n1] - '0' + carry;
            carry = sum / 10;
            int a = sum % 10;
            result.push_back(a + '0');
        }

        if (carry != 0)
            result.push_back(carry + '0');
        reverse(result.begin(), result.end());

        return result;
    }

    string multiply(string nums1, string nums2) {
        string result = "0";
        if(nums1 == "0" || nums2 == "0") return result;
        vector<string> tmpResult;
        int n1 = nums1.size();
        int n2 = nums2.size();

        int carry = 0;
        reverse(nums1.begin(),nums1.end());
        reverse(nums2.begin(),nums2.end());

        for (int i = 0; i < n1; i++) {
            string str;
            for (int j = 0; j < n2; j++) {
                int sum = (nums1[i] - '0') * (nums2[j] - '0') + carry;
                carry = sum / 10;
                int a = sum - carry * 10;
                str.push_back(a + '0');
            }
            if (carry != 0)
                str.push_back(carry+'0');
            carry = 0;
            reverse(str.begin(), str.end());
            for (int k = 0; k < i; k++) {
                str.push_back('0');
            }
            tmpResult.push_back(str);
        }

        int size = tmpResult.size();

        for (int i = 0; i < size; i++) {
            result = addTwoString(result, tmpResult[i]);
        }
        return result;
    }
};

 

 

转载于:https://www.cnblogs.com/wxquare/p/5216465.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值