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.

思路

最后要对结果进行校正,因为有可能 result[i]>10 .

        while(i<result.size()) {
            result[i+1] += result[i]/10;
            result[i] = result[i]%10; 
            i++;
        }

完整代码:

class Solution {
public:
    string multiply(string num1, string num2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len1 = num1.length();
        int len2 = num2.length();
        if(len1==0 || len2==0)
            return "0";
        vector<int> result(len1+len2+2,0);
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        for(int i=0;i<len1;i++){
            for(int j=0;j<len2;j++) {
                int a = num1[i]-'0';
                int b = num2[j]-'0';
                int product = a*b;
                result[i+j] += product%10;
                result[i+j+1] += product/10;       
            }
        }
        int i=0;
        while(i<result.size()) {
            result[i+1] += result[i]/10;
            result[i] = result[i]%10; 
            i++;
        }
        string res = "";
        int k = len1+len2+1;
        while(result[k]==0) k--;
        if(k==-1) return "0";
        while(k>=0) {
            res = res+char(result[k]+'0');
            k--;
        }
        return res;
    }
};

也有其他代码:

从后往前计算

string multiply(string num1, string num2) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    if (!num1.compare("0") || !num2.compare("0")) return "0";

    int len1 = num1.length();
    int len2 = num2.length();
    string result(len1+len2, '0');
    int tmp, carry;
    int i, j;

    for (j = len2-1; j >= 0; j--) {
        carry = 0;
        for (i = len1-1; i >= 0; i--) {
            tmp = (num1[i]-'0') * (num2[j]-'0') + carry + (result[i+j+1]-'0');
            carry = tmp / 10;
            result[i+j+1] = (tmp % 10) + '0';
        }
        result[j] = carry + '0';
    }

    if (result[0] == '0') {
        return string(result.begin()+1, result.end());
    }
    else {
        return result;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值