目錄鏈接:
力扣編程題-解法匯總_分享+記錄-CSDN博客
GitHub同步刷題項目:
https://github.com/September26/java-algorithms
原題鏈接:力扣(LeetCode)官網 - 全球極客摯愛的技術成長平臺
描述:
給定兩個以字符串形式表示的非負整數?num1
?和?num2
,返回?num1
?和?num2
?的乘積,它們的乘積也表示為字符串形式。
注意:不能使用任何內置的 BigInteger 庫或直接將輸入轉換為整數。
示例 1:
輸入: num1 = "2", num2 = "3" 輸出: "6"
示例?2:
輸入: num1 = "123", num2 = "456" 輸出: "56088"
提示:
1 <= num1.length, num2.length <= 200
num1
?和?num2
?只能由數字組成。num1
?和?num2
?都不包含任何前導零,除了數字0本身。
解題思路:
* 解題思路:
* 我們就按照乘法的定義來,把num1和num2轉換成兩個int類型的數組v1和v2。
* 然后用v2的每一位乘以v1數組,得到一個新的數組。比如v1是[1,2,3],v2的位置上的數字位2,得到的結果就是[2,4,6]。
* 然后我們可以得到多個這樣的數組,求這些數組的和即可。注意的時,后面的數組,前面要插入若干個0.
* 比如200和[1,2,3],前面就需要插入兩個0.
代碼:
class Solution43
{
public:vector<int> multiplyItem(vector<int> v1, int value){vector<int> result;int carryValue = 0;for (int i : v1){int newValue = value * i + carryValue;carryValue = newValue / 10;result.push_back(newValue % 10);}if (carryValue > 0){result.push_back(carryValue);}return result;}/*** 兩個list合并*/vector<int> merge(vector<int> oldList, int startIndex, vector<int> newList){for (int i = 0; i < startIndex; i++){newList.insert(newList.begin(), 0);}int index = 0;int carry = 0;vector<int> list;while (index < oldList.size() || index < newList.size() || carry > 0){int oldValue = 0;int newValue = 0;if (index < oldList.size()){oldValue = oldList[index];}if (index < newList.size()){newValue = newList[index];}int value = oldValue + newValue + carry;carry = value / 10;list.push_back(value % 10);index++;}return list;}string multiply(string num1, string num2){vector<int> v1;vector<int> v2;for (char c : num1){v1.insert(v1.begin(), c - '0');}for (char c : num2){v2.insert(v2.begin(), c - '0');}vector<int> result;int index = 0;int leftStart = 0;for (int i = 0; i < v2.size(); i++){vector<int> newList = multiplyItem(v1, v2[i]);result = merge(result, i, newList);}string s;bool isStart = false;for (int i = 0; i < result.size(); i++){s.insert(0, to_string(result[i]));}string ss;for (char c : s){if (ss.size() == 0 && c == '0'){continue;}ss.push_back(c);}return ss.size() == 0 ? "0" : ss;}
};