LeetCode 43 Multiply Strings(高精度乘法)
2017-10-20 17:02
525 查看
discription
给定两个非负数,num1和
num2,计算它们的乘积。
注意:
数字的长度小于110.数字只包含0-9.
数字不包含前导零
不能使用内置关于大数的库文件
solution
高精度乘法,其中需要用到高精度加法。code
class Solution { public: string add(string str1, string str2) //高精度加法 { string str; int len1 = str1.length(); int len2 = str2.length(); //前面补0,弄成长度相同 if (len1 < len2) { for (int i = 1; i <= len2 - len1; i++) str1 = "0" + str1; } else { for (int i = 1; i <= len1 - len2; i++) str2 = "0" + str2; } len1 = str1.length(); int cf = 0; int temp; for (int i = len1 - 1; i >= 0; i--) { temp = str1[i] - '0' + str2[i] - '0' + cf; cf = temp / 10; temp %= 10; str = char(temp + '0') + str; } if (cf != 0) str = char(cf + '0') + str; return str; } string multiply(string str1, string str2) { if (str1 == "0" || str2 == "0") return "0"; string str; int len1 = str1.length(); int len2 = str2.length(); string tempstr; for (int i = len2 - 1; i >= 0; i--) { tempstr = ""; int temp = str2[i] - '0'; int t = 0; int cf = 0; if (temp != 0) { for (int j = 1; j <= len2 - 1 - i; j++) tempstr += "0"; for (int j = len1 - 1; j >= 0; j--) { t = (temp * (str1[j] - '0') + cf) % 10; cf = (temp * (str1[j] - '0') + cf) / 10; tempstr = char(t + '0') + tempstr; } if (cf != 0) tempstr = char(cf + '0') + tempstr; } str = add(str, tempstr); } str.erase(0, str.find_first_not_of('0')); return str; } };
相关文章推荐
- LeetCode 43 Multiply Strings
- [LeetCode] 415 Add Strings && 67 Add Binary && 43 Multiply Strings
- leetcode 43: Multiply Strings
- LeetCode43 Multiply Strings
- 【leetcode】【43】Multiply Strings
- leetcode43 Multiply Strings
- leetcode(43) - Multiply Strings
- LeetCode 43 Multiply Strings
- Leetcode 43 Multiply Strings
- 【LeetCode】43. Multiply Strings
- [Leetcode]#43 Multiply Strings
- LeetCode_43---Multiply Strings
- LeetCode(43) Multiply Strings
- LeetCode - 43. Multiply Strings
- LeetCode(43)Multiply Strings
- LeetCode_OJ【43】Multiply Strings
- leetcode 43:Multiply Strings
- Leetcode 43. Multiply Strings
- Leetcode 43 Multiply Strings
- LeetCode(43)Multiply Strings