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

Multiply Strings

时间:2014-10-05 20:05:58      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   c   

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

 

大数乘法,直接用例子模拟算法,比如321*25

下标 0 1 2
num1 3 2 1
num2 2 5  

 

 

 

    3 2 1
      2 5
321分别乘以5   15 10 5
321分别乘以2 6 4 2  
上两行相加 6 19 12 5
处理进位得到结果 8 0 2 5
下标 0 1 2 3

 

 

 

 

 

 

 

模拟发现中间结果值存放位置下标与num1和num2中数下标对应关系,假设i 是num1的元素的下标,j 是num2中元素的下标,那么num1[i] * num[j] 存放在 i+j 中,由于需要处理进位,那么可以最前面留出一个元素空位

m位乘数 * n位乘数的结果最长为m+n位

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         if( num1.empty() || num2.empty() ) return string();
 5         vector<int> num(num1.length()+num2.length(), 0);    //结果最长为m+n位
 6         for(int i=0; i<num1.length(); ++i)
 7             for(int j=0; j<num2.length(); ++j)
 8                 num[i+j+1] += (num1[i]-0) * (num2[j]-0);    //放在i+j+1位,让num[0]空出,好处理进位
 9         int carry = 0;
10         for(int i=num.size()-1; i>=0; --i) {    //从后往前处理进位
11             int sum = num[i] + carry;
12             num[i] = sum % 10;
13             carry = sum / 10;
14         }
15         int idx = 0;
16         while( idx < num.size() && num[idx] == 0 ) ++idx;   //寻找第一个不为0的数
17         if( idx >= num.size() ) return string("0"); //找不到,说明结果为0
18         string ans;
19         while( idx < num.size() ) {
20             ans.push_back(num[idx]+0);    //输出到字符串中
21             ++idx;
22         }
23         return ans;
24     }
25 };

 

Multiply Strings

标签:style   blog   color   io   ar   for   sp   div   c   

原文地址:http://www.cnblogs.com/bugfly/p/4007187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!