首页 > 其他 > 详细

<LeetCode OJ> 43. Multiply Strings

时间:2016-01-24 22:33:14      阅读:309      评论:0      收藏:0      [点我收藏+]

43. Multiply Strings

My Submissions
Total Accepted: 51859 Total Submissions: 231017 Difficulty: Medium

以字符串的形式给定两个数字,返回相乘的结果,注意:结果也是字符串,因为数字可能很大

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.

Subscribe to see which companies asked this question

Hide Tags
 Math String
Show Similar Problems


分析:

代码注释已经很详细,模拟手算即可

//思路首先:
//模拟手算过程即可
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--)
        {
            int n1=num1[i]-'0';
            for(int j=num2.size()-1;j>=0;j--)
            {
                int n2=num2[j]-'0';
                tmpresult[i+j+1]+= n1*n2;
            }
        }
        //进位
        for(int i=allLen-1;i>0;i--)
        {
            while(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 OJ> 43. Multiply Strings

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!