LeetCode 43. 字符串相乘(大数乘法)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 43. 字符串相乘(大数乘法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 小學豎式乘法
- 2.1 普通版
- 2.2 優(yōu)化版
1. 題目
給定兩個以字符串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示為字符串形式。
示例 1: 輸入: num1 = "2", num2 = "3" 輸出: "6"示例 2: 輸入: num1 = "123", num2 = "456" 輸出: "56088"說明: num1 和 num2 的長度小于110。 num1 和 num2 只包含數字 0-9。 num1 和 num2 均不以零開頭,除非是數字 0 本身。 不能使用任何標準庫的大數類型(比如 BigInteger)或轉換為整數來處理。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/multiply-strings
著作權歸領扣網絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
類似題目:LeetCode 415. 字符串相加(大數加法)
2. 小學豎式乘法
2.1 普通版
class Solution { public:string multiply(string num1, string num2) {if(num1 == "0" || num2 == "0")return "0";int n1 = num1.size(), n2 = num2.size(), i, j;int bit1, bit2, carry, zero, curBit;string ans, temp;for(i = n2-1; i >= 0; i--){carry = 0;//進位清零temp = "";//臨時乘積zero = n2-1-i;//后置添0個數while(zero--)temp.push_back('0');bit2 = num2[i]-'0';for(j = n1-1; j >= 0 || carry != 0; --j){bit1 = j < 0 ? 0 : (num1[j]-'0');curBit = (bit1*bit2+carry)%10;temp.push_back(curBit+'0');carry = (bit1*bit2+carry)/10;}reverse(temp.begin(),temp.end());//上面臨時乘積是逆序的ans = addStrings(ans,temp);//調用大數加法}return ans;}//LeetCode 415. 字符串相加(大數加法)string addStrings(string num1, string num2) {int n1 = num1.length(), n2 = num2.length();int i = n1-1, j = n2-1, one = 0, bit1, bit2, curBit;string ans;for( ; i >= 0 || j >= 0; --i,--j){bit1 = i<0 ? 0 : (num1[i]-'0');bit2 = j<0 ? 0 : (num2[j]-'0');curBit = (bit1+bit2+one)%10;one = (bit1+bit2+one)/10;ans.push_back(curBit+'0');}if(one)ans.push_back('1');reverse(ans.begin(),ans.end());return ans;} };2.2 優(yōu)化版
class Solution { public:string multiply(string num1, string num2) {if(num1 == "0" || num2 == "0")return "0";int n1 = num1.size(), n2 = num2.size(), i, j, curSum;int bit1, bit2, len = n1+n2;int res[len] = {0};//兩數的乘積最多是n1+n2位string ans, temp;for(i = n2-1; i >= 0; i--){bit2 = num2[i]-'0';for(j = n1-1; j >= 0; --j){bit1 = num1[j]-'0';curSum = res[i+j+1] + bit1*bit2;res[i+j+1] = curSum % 10;res[i+j] += curSum / 10;}}for(i = 0; i < len; ++i){if(i == 0 && res[i] == 0)continue;//前面可能有一個0,跳過ans.append(to_string(res[i]));}return ans;} };總結
以上是生活随笔為你收集整理的LeetCode 43. 字符串相乘(大数乘法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LintCode 1753. 写作业(二
- 下一篇: 剑指Offer - 面试题62. 圆圈中