[LeetCode] Multiply Strings 解题报告
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Multiply Strings 解题报告
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative.? Solve this problem
[解題思路]
大整數乘法,一位一位往上乘,注意進位的處理即可。此外,注意0的處理
[Code]
1: string multiply(string num1, string num2) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: if(num1.size() ==0 || num2.size() ==0) return 0;
5: string res(num1.size()+num2.size()+1, '0');
6: std::reverse(num1.begin(), num1.end());
7: std::reverse(num2.begin(), num2.end());
8: for(int i =0; i < num1.size(); i++)
9: {
10: int dig1 = num1[i] -'0';
11: int carry = 0;
12: for(int j = 0; j< num2.size(); j++)
13: {
14: int dig2 = num2[j] - '0';
15: int exist = res[i+j] -'0';
16: res[i+j] = (dig1*dig2+carry+ exist) % 10 +'0';
17: carry = (dig1*dig2+carry+exist)/10;
18: }
19: if(carry >0)
20: {
21: res[i+num2.size()] = carry + '0';
22: }
23: }
24: std::reverse(res.begin(), res.end());
25: int start =0;
26: while(res[start] =='0' && start < res.size())
27: {
28: start++;
29: }
30: if(start == res.size()) return "0";
31: return res.substr(start, res.size()-start);
32: }
[Note]
1. Line 25~31, 處理乘法過程中在起始處產生的0。 比如, “9133”, “0”,直接乘的結果是“000000”, 而期待結果是“0”
轉載于:https://www.cnblogs.com/codingtmd/archive/2012/12/28/5078984.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的[LeetCode] Multiply Strings 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云南丽江必买特产
- 下一篇: 家具厂价直销宣传文案28句