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

leetcode. Multiply Strings

时间:2014-11-13 23:47:53      阅读:177      评论:0      收藏:0      [点我收藏+]

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

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.

 大数乘法主要有以下方法:

1、按照乘法法则直接乘,算法较简单,时间复杂度O(n^2)

2、分治法。

3、快速数论变换FNTT

2和3实现比较复杂,本次只完成1.

 1     string multiply(string num1, string num2)
 2     {
 3         int i, j;
 4         int m = num1.length(), n = num2.length();
 5         char *ret = new char[m + n + 1]; 
 6         string sret = ""; 
 7         
 8         if ((num1 == "0") || (num2 == "0"))
 9             return "0";
10         reverse(num1.begin(), num1.end());
11         reverse(num2.begin(), num2.end());
12         memset(ret, 0, m + n); 
13         for (i = 0; i < m; i++)
14         {   
15             for (j = 0; j < n; j++)
16             {   
17                 int temp = (num1[i] - 0) * (num2[j] - 0);
18                 ret[i + j] += temp % 10; 
19                 if (ret[i + j] > 9)
20                 {   
21                     int at = ret[i + j]; 
22                     ret[i + j] = at % 10;   
23                     ret[i + j + 1] += at / 10;  
24                 }   
25                 ret[i + j + 1] += temp / 10; 
26             }
27         }
28     
29         i = m + n - 1;
30         while (0 == ret[i])
31             i--;
32         while (i >= 0)
33         {
34             sret += (ret[i] + 0);
35             i--;
36         }
37     
38         delete[] ret;
39         return sret;
40     }

 

leetcode. Multiply Strings

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

原文地址:http://www.cnblogs.com/ym65536/p/4095978.html

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