[LeetCode] 059: Multiply Strings
2017-09-10 20:50
197 查看
[Problem]
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.
[Solution]
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.
[Solution]
class Solution { public: /** * calculate the sum of the numbers */ string add(string num1, string num2){ string res = ""; int sum = 0, carry = 0; int i = num1.size() - 1, j = num2.size() - 1; while(i >= 0 || j >= 0){ sum = carry; if(i >= 0){ sum += num1[i--] - '0'; } if(j >= 0){ sum += num2[j--] - '0'; } carry = sum / 10; sum %= 10; res = string(1, char(sum + '0')) + res; } if(carry > 0){ res = string(1, char(carry + '0')) + res; } // remove head '0' i = 0; while(i < res.size() && res[i] == '0')i++; // return if(i == res.size()){ return "0"; } else{ return res.substr(i, res.size() - i); } } /** * multiply the two strings */ string multiply(string num1, string num2) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<string> numbers; string tail = ""; for(int i = num2.size()-1; i >= 0; --i){ string tmp = ""; int carry = 0, res = 0; for(int j = num1.size()-1; j >= 0; --j){ res = carry + (num2[i] - '0') * (num1[j] - '0'); carry = res / 10; res %= 10; tmp = string(1, char(res + '0')) + tmp; } if(carry > 0){ tmp = string(1, char(carry + '0')) + tmp; } tmp += tail; tail += "0"; numbers.push_back(tmp); } // add the numbers string sum = "0"; for(int i = 0; i < numbers.size(); ++i){ sum = add(sum, numbers[i]); } return sum; } };说明:版权所有,转载请注明出处。Coder007的博客
相关文章推荐
- leetcode:Multiply Strings
- leetcode(43) - Multiply Strings
- Sum—LeetCode-43 Multiply Strings
- [Leetcode] #43 Multiply Strings
- Java for LeetCode 043 Multiply Strings
- [LeetCode] Multiply Strings 解题报告
- leetcode--Multiply Strings
- Multiply Strings[LeetCode]
- LeetCode Multiply Strings
- LeetCode | Multiply Strings
- leetcode---multiply-strings---字符串
- [Leetcode]Multiply Strings
- leetcode解题方案--043-- Multiply Strings
- 【LeetCode】Multiply Strings
- LeetCode 42 Multiply Strings
- leetcode 043 —— Multiply Strings
- [leetcode] Multiply Strings
- [LeetCode]043-Multiply Strings
- Leetcode | Multiply Strings
- [LeetCode] Multiply Strings