LeetCode 43. Multiply Strings
来源:互联网 发布:terminal mac 编辑:程序博客网 时间:2024/06/07 05:31
题意
求两个字符串表示的数字相乘
思路
可能会很大,所以说使用字符串处理,模拟乘法的步骤,分解一个数的每一位和另一个数相乘,然后将得出的数加起来即可.
代码
class Solution {public: string multiply(string num1, string num2) { size_t len1 = num1.length(); size_t len2 = num2.length(); if(num1 == "0" || num2 == "0"){ return "0"; } vector<string>temp; for(int i = 0; i < len2; i++){ temp.push_back(mul(num1, num2[i] - '0')); } reverse(temp.begin(), temp.end()); string ans = temp[0]; int cnt = 0; //添加末尾0,模拟进位 for(int i = 1; i < len2;i++){ string zero = ""; for(int j = 0; j < i; j++) zero += "0"; ans = add(ans, temp[i] + zero); } return ans; }private: //两个字符串数相加 string add(string A, string B){ int lenA = A.length(); int lenB = B.length(); string ans = ""; lenA--;lenB--; int pos = 0; while(lenA >= 0 && lenB >= 0){ int sum = A[lenA--] + B[lenB--] - '0' - '0' + pos; ans += sum % 10 + '0'; pos = sum / 10; } while(lenA >= 0){ int sum = A[lenA--]- '0' + pos; ans += sum % 10 + '0'; pos = sum / 10; } while(lenB >= 0){ int sum = B[lenB--]- '0' + pos; ans += sum % 10 + '0'; pos = sum / 10; } if(pos) ans += pos + '0'; reverse(ans.begin(), ans.end()); return ans; } //一个字符串数和一个数相乘 string mul(string num, int val){ int len = num.length(); string ans = ""; len--; int pos = 0; while(len >= 0){ int mulNum = (num[len--] - '0') * val + pos; ans += mulNum % 10 + '0'; pos = mulNum / 10; } if(pos) ans += pos + '0'; reverse(ans.begin(), ans.end()); return ans; }};
阅读全文
0 0
- [LeetCode]43.Multiply Strings
- LeetCode --- 43. Multiply Strings
- [Leetcode] 43. Multiply Strings
- [leetcode] 43.Multiply Strings
- 43. Multiply Strings LeetCode
- 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] 43. Multiply Strings
- leetcode 43. Multiply Strings
- Leetcode 43. Multiply Strings
- leetcode 43. Multiply Strings
- unicode为12288字符
- java客户端操作fastdfs集群
- 【Angular2】You have to be inside an angular-cli project in order to use the generate command
- web的Seo搜索优化
- 堆知识总结
- LeetCode 43. Multiply Strings
- 函数的高阶特性——Python学习笔记04
- 使用Travis CI自动打包APK,并发布到fir
- JSplitPane 监听分割位置
- 用Swift 给tableView加载xib创建的tableHeaderView时不显示问题
- Android问题:com.android.builder.packaging.DuplicateFileException
- eq相等 ne、neq不相等, gt大于, lt小于 gte、ge大于等于 lte、le 小于等于 not非 mod求模 等
- 在逻辑学中,SAP,SEP,SIP,SOP,SaP,SeP分别是什么意思?
- java基础教程:基础语法之术语和入口类(2)