【LeetCode】43. Multiply Strings

题目描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题思路

大数相乘。
为了解题思路清晰,我是自己模拟手工相乘的方法做的。具体见代码注释。

AC代码

class Solution {
public:
    //给数组左边加0,使其最终长度为tLen
    string leftPad(string num, int tLen) {
        int numLen = num.size();
        string zero(tLen - numLen, '0');
        return zero + num;
    }
    //大数相加。先将两个大数前面补0使其长度相同,注意最后的carry
    string strAdd(string num1, string num2) {
        int maxLen = max(num1.size(), num2.size());
        num1 = leftPad(num1, maxLen);
        num2 = leftPad(num2, maxLen);

        string ans;
        int carry = 0;
        for (int idx = maxLen - 1; idx >= 0; --idx) {
            int curSum = (num1[idx] - '0') + (num2[idx] - '0');
            curSum += carry;
            ans.push_back((curSum % 10) + '0');
            carry = curSum / 10;
        }
        if (carry != 0)
            ans.push_back(carry + '0');

        reverse(ans.begin(), ans.end());

        return ans;
    }
    //大数相乘。每次使用一个位与另一个数字相乘,然后通过大数相加更新答案。
    string multiply(string num1, string num2) {
        if (num2 == "0" || num1 == "0")
            return "0";

        string ans;
        for (int i = num2.size() - 1; i >= 0; --i) {
            if (num2[i] == '0')
                continue;

            string curAns;
            int carry = 0;
            for (int j = num1.size() - 1; j >= 0; --j) {
                int mul = (num2[i] - '0') * (num1[j] - '0');
                mul += carry;
                curAns.push_back((mul % 10) + '0');
                carry = mul / 10;
            }
            if (carry != 0)
                curAns.push_back(carry + '0');

            reverse(curAns.begin(), curAns.end());
            string zeros(num2.size() - i - 1, '0');
            ans = strAdd(ans, curAns + zeros);
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值