码迷,mamicode.com
首页 > 其他好文 > 详细

<LeetCode OJ> 43. Multiply Strings

时间:2016-01-24 22:33:22      阅读:193      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!