leetcode: Multiply Strings
2013-11-07 15:27
435 查看
http://oj.leetcode.com/problems/multiply-strings/
思路:
这是一道经常出现的面试题。竖式乘法怎么做的照搬就可以,注意看代码,用一个string搞定。
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.
思路:
这是一道经常出现的面试题。竖式乘法怎么做的照搬就可以,注意看代码,用一个string搞定。
class Solution { public: string multiply(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); if (("0" == num1) || ("0" == num2)) { return "0"; } string result = ""; int i, j; int flag = 0, steps = 0; for (int i = 0; i < num1.length(); ++i) { int position = steps; for (int j = 0; j < num2.length(); ++j) { int v = (num1[i] - '0') * (num2[j] - '0') + flag; if (position < result.length()) { v += result[position] - '0'; result[position] = (v % 10) + '0'; } else { result.append(1, (v % 10) + '0'); } flag = v / 10; ++position; } if (flag > 0) { result.append(1, flag + '0'); } flag = 0; ++steps; } reverse(result.begin(), result.end()); return result; } };
相关文章推荐
- leetcode(43)Multiply Strings
- [leetcode] Multiply Strings
- Leetcode_multiply-strings (updated c++ and python version)
- LeetCode Multiply Strings 大数相乘
- LeetCode 43 Multiply Strings
- LeetCode 043 Multiply Strings
- 【leetcode】Multiply Strings
- [LeetCode]题解(python):043-Multiply Strings
- Multiply Strings leetcode java
- LeetCode-Multiply Strings
- [Leetcode] Multiply strings 字符串对应数字相乘
- [leetcode] Multiply Strings
- Multiply Strings--LeetCode
- leetcode--Multiply Strings
- [Leetcode] #43 Multiply Strings
- leetcode Multiply Strings
- [LeetCode] Multiply Strings
- LeetCode:Multiply Strings
- 大整数乘法--leetcode Multiply Strings
- [LeetCode] 415 Add Strings && 67 Add Binary && 43 Multiply Strings