leetcode 43. 字符串相乘(Multiply Strings)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 43. 字符串相乘(Multiply Strings)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 題目描述:
- 示例 1:
- 示例 2:
- 解法:
題目描述:
給定兩個以字符串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示為字符串形式。
示例 1:
輸入: num1 = "2", num2 = "3" 輸出: "6"示例 2:
輸入: num1 = "123", num2 = "456" 輸出: "56088"說明:
解法:
class Solution { public:string multi(string& s, char ch){if(ch == '0'){return "0";}else if(ch == '1'){return s;}string res = "";int sz = s.size();int carry = 0;for(int i = sz-1; i >= 0; i--){int val = carry + int(s[i] - '0')*int(ch - '0');carry = val / 10;val %= 10;res = char(val + '0') + res;}if(carry != 0){res = char(carry + '0') + res;}return res;}string add(const string& s, const string& t){string res = "";int sz1 = s.size();int sz2 = t.size();int i = sz1-1, j = sz2-1;int carry = 0;while(i >= 0 || j >= 0 || carry > 0){int d1 = (i >= 0) ? int(s[i] - '0') : 0;int d2 = (j >= 0) ? int(t[j] - '0') : 0;int d = d1 + d2 + carry;carry = d/10;d %= 10;res = char(d + '0') + res;i--;j--;}return res;}string multiply(string num1, string num2) {if(num1 == "0" || num2 == "0"){return "0";}else{int sz1 = num1.size();int sz2 = num2.size();string s = num1, t = num2;if(sz1 <= sz2){t = num1;s = num2;}string res = "";for(char ch : t){res += '0';res = add(res, multi(s, ch));}return res;}} };轉載于:https://www.cnblogs.com/zhanzq/p/10697358.html
總結
以上是生活随笔為你收集整理的leetcode 43. 字符串相乘(Multiply Strings)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实训作业
- 下一篇: 前端小白第一次使用redux存取数据练习