LeetCode Multiply Strings
阿新 • • 發佈:2019-01-25
Given two non-negative integers num1
and num2
represented
as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library
看到這個題目的第一反應就是大整數的計算器。。。 冒出兩個思路:1.將字串轉換為整數,進行相乘,然後將結果轉換為字串。當然這鐘方法是無法處理好溢位問題的 2.大整數乘法的過程可知,可以通過個位數與大整數的乘法以及大整數加法來完成
思路一:不實現大整數加法來完成大整數乘法,通過將大整數乘法的過程再進行細分。num1的i位和num2的j位相乘,得到數為mul,因為存在進行位的關係,需要將mul和正在生成的結果的i+j+1相加得到sum,sum的個位數將分配在i+j+1位上,sum的十位數將分配在i+j位上
程式碼如下:
class Solution { public: string multiply(string num1, string num2) { int m=num1.length(),n=num2.length(); int *p = new int[m+n]; memset(p,0,sizeof(int)*(m+n)); for(int i=m-1;i>=0;i--) { for(int j=n-1;j>=0;j--) { int mul = (num1[i]-'0')*(num2[j]-'0'); int sum = p[i+j+1] +mul ; p[i+j] += sum/10; p[i+j+1] = sum%10; } } string res; string temp; for(int i=0;i<m+n;i++) { if(!(res.length() == 0 && p[i] == 0)) { temp = p[i]+'0'; res.append(temp); } } return res.length() == 0?"0":res; } };
發現有個思路差不多的,但是編寫出來的效率更高,貼出來研究下:
class Solution {
public:
string multiply(string num1, string num2) {
string sum(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; 0 <= i; --i) {
int carry = 0;
for (int j = num2.size() - 1; 0 <= j; --j) {
int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
sum[i + j + 1] = tmp % 10 + '0';
carry = tmp / 10;
}
sum[i] += carry;
}
size_t startpos = sum.find_first_not_of("0");
if (string::npos != startpos) {
return sum.substr(startpos);
}
return "0";
}
};
通過對比可以發現,第一份程式碼多出了將int陣列轉換為string的開銷