Leetcode 43 - Multiply Strings(高精度乘)

23 篇文章 0 订阅
6 篇文章 0 订阅

题意

实现高精度乘法。

思路

模拟即可,但是模拟也是有方法的。

算法1

直接像我们手算乘法一样模拟,每次计算出来的一位都要保证小于10并且记录进位。

过程如下:

这里写图片描述

算法2

比算法1简单很多。

还是像手算乘法一样,但是比如我们算出来某一位相乘大于等于10后,我们不进位,直接保留结果,在最后的时候再统一进位。

还是上面那个例子:

这里写图片描述

时间复杂度: O(mn) (其中m和n分别是两个字符串的长度)

代码

algorithm 1

class Solution {
public:
    string add(string x, string y) {
        string s = "";
        int i = x.length() - 1, j = y.length() - 1, adc = 0;
        while (i >= 0 || j >= 0 || adc) {
            int t = (i >= 0 ? x[i] - '0' : 0) + (j >= 0 ? y[j] - '0' : 0) + adc;
            if (t >= 10) {adc = t / 10; t %= 10;}
            else adc = 0;
            s = char(t + '0') + s;
            i--, j--;
        }
        return s;

    }

    string mul(string x, char y) {
        string s = "";
        int z = y - '0', adc = 0;
        for (int i = x.length() - 1; i >= 0; i--) {
            int t = (x[i] - '0') * z + adc;
            if (t > 10) {
                adc = t / 10;
                t %= 10;
            } else {
                adc = 0;
            }
            s = char(t + '0') + s;
        }
        if (adc) s = char(adc + '0') + s;
        return s;
    }

    string multiply(string num1, string num2) {
        if (num1 == "" && num2 == "") return "";
        string pre = "", now = "";
        int t = 0;
        int m = num1.length(), n = num2.length();
        for (int j = n - 1; j >= 0; j--) {
            now = mul(num1, num2[j]);
            for (int i = 0; i < t; i++) now.push_back('0');
            pre = add(pre, now);
            t++;
        }
        if (pre[0] != '0') return pre;
        int i = 0;
        while (pre[i] == '0' && i < pre.length()) i++;
        if (i == pre.length()) return "0";
        return pre.substr(i, pre.length() - i + 1);
    }
};

algorithm 2

class Solution {
public:
    string multiply(string num1, string num2) {
        int m = num1.size(), n = num2.size();
        vector<int> tmp(m + n - 1, 0);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++)
                tmp[i + j] += (num1[i] - '0') * (num2[j] - '0');
        }
        string s = "";
        int adc = 0, i = tmp.size() - 1;
        while (i >= 0 || adc) {
            int t = (i >= 0 ? tmp[i] : 0) + adc;
            cout << t << ' ' ;
            if (t >= 10) {
                adc = t / 10;
                t %= 10;
            } else {
                adc = 0;
            }
            s = char(t + '0') + s;
            i--;
        }
        i = 0;
        while (i < s.length() && s[i] == '0') i++;
        if (i == s.length()) return "0";
        s.substr(i, s.length() - i + 1);
        return s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值