Multiply Strings

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 genZero(int n){//生成n个0组成的字符串
        string s = "";
        for(int i = 0; i < n; ++i)
            s += '0';
        return s;
    }
    string stringPlus(string num1, string num2){//字符串加法
        string s = "";
        int len1 = num1.length();
        int len2 = num2.length();
        if(len1 == 0)
            return num2;
        if(len2 == 0)
            return num1;
        int i = len1 - 1, j = len2 - 1;
        int jinwei = 0;
        while(i >= 0 && j >= 0){
            int a = num1[i--] - '0';
            int b = num2[j--] - '0';
            int c = a + b + jinwei;
            s += c % 10 + '0';
            jinwei = c / 10;
        }
        while(i >= 0){
            int a = num1[i--] - '0';
            int c = a + jinwei;
            s += c % 10 + '0';
            jinwei = c / 10;
        }
        while(j >= 0){
            int b = num2[j--] - '0';
            int c = b + jinwei;
            s += c % 10 + '0';
            jinwei = c / 10;
        }
        if(jinwei){
            s += '1';
        }
        string sum = "";
        for(i = s.length() - 1; i >= 0; i--)
            sum += s[i];
        return sum;
    }
    string multiplyChar(string num, char c){//字符串乘以某一字符,例如“123” × ‘2’ = “246”
        int n = c - '0';//n=[0-9]
        if(n == 0)
            return "0";
        if(n == 1)
            return num;
        string ret = num;
        for(int i = 1; i < n; ++i){
            ret = stringPlus(num, ret);
        }
        return ret;
    }
    string multiply(string num1, string num2){//字符串乘法
        int len1 = num1.length();
        int len2 = num2.length();
        if(len1 == 0 || len2 == 0)
            return "";
        if(len1 > len2){
            swap(num1, num2);
            swap(len1, len2);
        }
        string ret = "";
        for(int i = len1 - 1; i >= 0; --i){
            string tmp = multiplyChar(num2, num1[i]) + genZero(len1 - 1 - i);
            ret = stringPlus(ret, tmp);
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值