LeetCode: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

大整数乘法


我们以289*785为例

image

 

首先我们把每一位相乘,得到一个没有进位的临时结果,如图中中间的一行红色数字就是临时结果,然后把临时结果从低位起依次进位。对于一个m位整数乘以n位整数的结果,最多只有m+n位。         本文地址

注意:结果中需要去掉前导0,还需要注意结果为0的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class  Solution {
public :
     string multiply(string num1, string num2) {
         int  n1 = num1.size(), n2 = num2.size();
         vector< int > tmpres(n1+n2, 0);
         int  k = n1 + n2 - 2;
         for ( int  i = 0; i < n1; i++)
             for ( int  j = 0; j < n2; j++)
                 tmpres[k-i-j] += (num1[i]- '0' )*(num2[j]- '0' );
         int  carryBit = 0;
         for ( int  i = 0; i < n1+n2; i++) //处理进位
         {
             tmpres[i] += carryBit;
             carryBit = tmpres[i] / 10;
             tmpres[i] %= 10;
         }
         int  i = k+1;
         while (tmpres[i] == 0)i--; //去掉乘积的前导0
         if (i < 0) return  "0" ; //注意乘积为0的特殊情况
         string res;
         for (; i >= 0; i--)
             res.push_back(tmpres[i] + '0' );
         return  res;
     }
};

 

上述算法的复杂度为O(n^2)(假设整数长度为n)

另外更高效的计算大整数乘法一般有:(1)karatsuba算法,复杂度为3nlog3≈3n1.585,可以参考百度百科面试题——大整数乘法乘法算法-Karatsuba算法。(2)基于FFT(快速傅里叶变换)的算法,复杂度为o(nlogn), 可以参考FFT, 卷积, 多项式乘法, 大整数乘法






本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3735309.html,如需转载请自行联系原作者

目录
相关文章
|
人工智能 算法
LeetCode 1347. 制造字母异位词的最小步骤数 Minimum Number of Steps to Make Two Strings Anagram
LeetCode 1347. 制造字母异位词的最小步骤数 Minimum Number of Steps to Make Two Strings Anagram
LeetCode 415. Add Strings
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
67 0
LeetCode 415. Add Strings
LeetCode 205. Isomorphic Strings
给定两个字符串 s 和 t,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
57 0
LeetCode 205. Isomorphic Strings
LeetCode 43. Multiply Strings
给定两个表示为字符串形式的非负整数num1和num2,返回num1和num2的乘积,也表示为字符串形式。
52 0
LeetCode 43. Multiply Strings
|
Java 索引 Python
LeetCode 205:同构字符串 Isomorphic Strings
题目: 给定两个字符串 s 和 *t*,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 *t* ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
869 0
leetcode 205. Isomorphic Strings
题目 Given two strings s and t, determine if they are isomorphic.
679 0
LeetCode - 43. Multiply Strings
43. Multiply Strings  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定两个字符串,计算这两个字符串相乘的结果.
905 0
|
索引 Java
LeetCode 205 Isomorphic Strings(同构的字符串)(string、vector、map)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50611168 翻译 给定两个字符串s和t,决定它们是否是同构的。
829 0