題目描述
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
給定兩個(gè)以字符串形式表示的非負(fù)整數(shù) num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示為字符串形式。
num1 和 num2 的長(zhǎng)度小于110。
num1 和 num2 只包含數(shù)字 0-9。
num1 和 num2 均不以零開(kāi)頭,除非是數(shù)字 0 本身。
不能使用任何標(biāo)準(zhǔn)庫(kù)的大數(shù)類型(比如 BigInteger)或直接將輸入轉(zhuǎn)換為整數(shù)來(lái)處理。
題解
由于題目要求:不能將字符串轉(zhuǎn)化成大整數(shù)來(lái)處理。所以需要換一種方法,這里打算模仿2個(gè)整數(shù)的計(jì)算過(guò)程,直接計(jì)算結(jié)果。
模仿自己手算整數(shù)的計(jì)算:把兩個(gè)數(shù)末尾對(duì)齊,固定一個(gè)數(shù)字a,從末尾開(kāi)始,依次用數(shù)字與另個(gè)整數(shù)b的末尾開(kāi)始相乘,計(jì)算進(jìn)位數(shù)、余數(shù);整數(shù)b遍歷完成后,將指向a中的數(shù)字向前移動(dòng)一位,反復(fù)計(jì)算,直到數(shù)字a遍歷完成。
值得注意的是:需要先設(shè)定一個(gè)字符串用戶存儲(chǔ)臨時(shí)的結(jié)果。所以,我們要明確字符串的長(zhǎng)度,設(shè)整數(shù)1、整數(shù)2長(zhǎng)度分別為m,n;那么乘法結(jié)果的最大長(zhǎng)度為m+n。兩個(gè)數(shù)字都遍歷完成后,對(duì)臨時(shí)結(jié)果從頭到尾進(jìn)行遍歷,舍去其中為‘0’的字符。
完整代碼:
class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size(), size2 = num2.size();
string res(size1+size2, '0');
for (int i=size1-1; i>=0; --i){
for (int j=size2-1; j>=0; --j){
int temp = (num1[i] - '0') * (num2[j] - '0') + (res[i+j+1] - '0');
res[i+j] += temp / 10 ;
res[i+j+1] = temp % 10 + '0';
}
}
for (int i=0; i< size1+size2; i++){
if (res[i] != '0')
return res.substr(i);
}
return "0";
}
};