43. Multiply Strings
2016-06-26 14:01
295 查看
题目:
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
题意:
以字符串的形式给出两个整数,同样以字符串的形式返回两个字符串的乘积;
note:
1、这些数字都可以任意大并且是非负的;
2、不允许将输入的字符串转化为整数;
3、不允许使用内部库函数,例如BigInteger。
思路:转载地址:https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation
根据基本乘法运算规则,从右到左将每一个数位依次对应相乘,之后相加起来。
`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]`
代码:java版:10ms
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
题意:
以字符串的形式给出两个整数,同样以字符串的形式返回两个字符串的乘积;
note:
1、这些数字都可以任意大并且是非负的;
2、不允许将输入的字符串转化为整数;
3、不允许使用内部库函数,例如BigInteger。
思路:转载地址:https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation
根据基本乘法运算规则,从右到左将每一个数位依次对应相乘,之后相加起来。
`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]`
代码:java版:10ms
public class Solution { public String multiply(String num1, String num2) { int m = num1.length(), n = num2.length(); int[] pos = new int[m+n]; for (int i=m-1; i>=0; i--) { for (int j=n-1; j>=0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i+j, p2 = i+j+1; int sum = mul + pos[p2]; pos[p1] += sum/10; pos[p2] = (sum)%10; } } StringBuilder sb = new StringBuilder(); for (int p : pos) { if (!(sb.length() == 0 && p == 0)) { sb.append(p); } } return sb.length() == 0 ? "0" : sb.toString(); } }代码:C++版:8ms
class Solution { public: string multiply(string num1, string num2) { string sum(num1.size() + num2.size(), '0'); for (int i=num1.size()-1; i>=0; i--) { int carry = 0; for (int j=num2.size()-1; j>=0; j--) { int tmp = (sum[i+j+1]-'0') + (num1[i] - '0') * (num2[j] - '0') + carry; sum[i+j+1] = tmp % 10 + '0'; carry = tmp / 10; } sum[i] += carry; } size_t startpos = sum.find_first_not_of("0"); if (string::npos != startpos) { return sum.substr(startpos); } return "0"; } };
相关文章推荐
- imx6 x264 ffmpeg 移植----fwqlzz love is for ever
- uva1601(The morning after Helloween)解题报告
- 每天一个Linux命令(19)--find命令
- 如何用在python中迭代一个列表以及字典的索引和值?
- 积分表
- SSIST 2016 参会总结--day3
- mac 下常用命令
- LeetCode之16_3Sum Closest
- 使用BaseAdapter时如何让listView更高效
- JSON.parse()和JSON.stringify()
- AWS存储
- 自我能力的提升方法
- Android App性能优化步骤及电量优化与service优化
- JAVAweb开发技术-------(一)Http协议
- Tomcat_修改代码后tomcat是否需要重启
- .NET的EF框架中:在应用程序配置文件中找不到名为“”的连接字符串问题
- 龙芯yl8089无声音的解决方案
- 静态链表
- 键入service iptables status/start/restart无任何反应
- LeetCode之15_3Sum