[leetcode] 43. Multiply Strings 解题报告
2016-02-21 15:03
555 查看
题目链接:https://leetcode.com/problems/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.
思路:用数组来模拟相乘,其结果的长度最多为(len1 + len2),最小为(len1 + len2 -1).并且两个位置i,j的字符相乘的结果的位置是(i+j),应还要考虑进位.
最后还要注意乘积为0的情况,应该将字符串变为只有一个0.
代码如下:
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.
思路:用数组来模拟相乘,其结果的长度最多为(len1 + len2),最小为(len1 + len2 -1).并且两个位置i,j的字符相乘的结果的位置是(i+j),应还要考虑进位.
最后还要注意乘积为0的情况,应该将字符串变为只有一个0.
代码如下:
class Solution { public: string multiply(string num1, string num2) { vector<int> vec(num1.size()+num2.size(), 0); reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); for(auto i = 0; i < num1.size(); i++) { for(auto j = 0; j < num2.size(); j++) { int tem = (num1[i]-'0') * (num2[j]-'0'); vec[i+j] = vec[i+j] + tem; vec[i+j+1] += vec[i+j]/10; vec[i+j] %= 10; } } while(vec.size() > 1 && vec[vec.size()-1] == 0) vec.resize(vec.size()-1); string ans; for(int i = vec.size()-1; i>= 0; i--) ans += to_string(vec[i]); return ans; } };
相关文章推荐
- 大数据工具——Splunk
- 正确使用C++引用做返回值和参数
- CSS 三角形绘制方法
- 234. Palindrome Linked List
- MongoDb的基本使用以和关系性数据库的基本差异
- Struts2 用DomainModel接收参数
- 网站概况分析可以认为是网站的“五官”检测
- android下数据库的创建
- 【HDOJ】4373 Mysterious For
- 对于其中具体的流程,也是要掌握好
- NSURLSession下载之断点续传
- Android五个进程等级(转)
- uva 11077 排列
- MySQL使用变量实现部分分组聚合
- 初识WCF
- 初识WCF
- Elasticsearch Scroll (游标)API详解
- 如何让你的网络平台成为一个巨大磁场
- 多态总结
- oracle之深入解析DML语句