<LeetCode OJ> 43. Multiply Strings

43. 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 multiply(string num1, string num2) {
        int allLen=num1.size()+num2.size();
        vector<int> tmpresult(allLen,0);
        string result(allLen,'0');
        //模拟手算从最后一位开始处理
        for(int i=num1.size()-1;i>=0;i--)
            for(int j=num2.size()-1;j>=0;j--)
                tmpresult[i+j+1]+= (num1[i]-'0')*(num2[j]-'0');
            
        //进位
        for(int i=allLen-1;i>0;i--)
        {
            if(tmpresult[i]>9)
            {
                tmpresult[i-1]+=tmpresult[i]/10;
                tmpresult[i]%=10;
            }
        }
        //转换成字符串
        for(int i=allLen-1;i>=0;i--)
            result[i]=tmpresult[i]+'0';
            
        if(result.find_first_not_of('0') == string::npos) 
            return "0";//排除全0的情况
        return result.substr(result.find_first_not_of('0'),string::npos);
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50575524

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值