leetcode 43:Multiply Strings
2015-11-04 20:25
387 查看
题目:
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.
思路:
可以按照我们一般做乘法的思路,用一个数的每一位去乘另一个数的每一位,将结果加在对应结果位中。结果的位数从第一位到(n1+n2)位。
时间复杂度O(n1*n2),空间复杂度O(n1+n2)。
需要注意两个进位操作,第一是两个位数相乘后的进位,第二个是将相乘结果相加时产生的进位。
第一个进位直接加到下一次乘积结果中,第二个进位则要加在高位的结果位中。
实现如下:
class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size(), size2 = num2.size();
string result(size1+size2,'0');
int mul = 0, carry = 0;
for (int i = size1 - 1; i >= 0; i--)
{
carry = 0;
int index = size1-1-i;
for (int j = size2 - 1; j >= 0; j--)
{
mul = (num1[i] - '0')*(num2[j] - '0');
int temp=result[index]-'0' + mul % 10 + carry ;
result[index + 1] += temp / 10;
result[index] = temp % 10 + '0';
carry = mul / 10;
index++;
}
result[index] += carry;
}
int pos = size1 + size2 - 1;
while (pos>0 && result[pos] == '0') pos--;
result[pos + 1] = '\0';
for (int i = 0; i <= pos / 2; i++)
{
swap(result[i],result[pos-i]);
}
return result.substr(0,pos+1);
}
};
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.
思路:
可以按照我们一般做乘法的思路,用一个数的每一位去乘另一个数的每一位,将结果加在对应结果位中。结果的位数从第一位到(n1+n2)位。
时间复杂度O(n1*n2),空间复杂度O(n1+n2)。
需要注意两个进位操作,第一是两个位数相乘后的进位,第二个是将相乘结果相加时产生的进位。
第一个进位直接加到下一次乘积结果中,第二个进位则要加在高位的结果位中。
实现如下:
class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size(), size2 = num2.size();
string result(size1+size2,'0');
int mul = 0, carry = 0;
for (int i = size1 - 1; i >= 0; i--)
{
carry = 0;
int index = size1-1-i;
for (int j = size2 - 1; j >= 0; j--)
{
mul = (num1[i] - '0')*(num2[j] - '0');
int temp=result[index]-'0' + mul % 10 + carry ;
result[index + 1] += temp / 10;
result[index] = temp % 10 + '0';
carry = mul / 10;
index++;
}
result[index] += carry;
}
int pos = size1 + size2 - 1;
while (pos>0 && result[pos] == '0') pos--;
result[pos + 1] = '\0';
for (int i = 0; i <= pos / 2; i++)
{
swap(result[i],result[pos-i]);
}
return result.substr(0,pos+1);
}
};
相关文章推荐
- Android 开启服务Service
- EhCache java缓存框架介绍
- iOS开发中JSON文件的加载
- LeetCode---Plus One
- C++设计模式[五]适配器模式
- 第二章 认识Axure RP
- POJ Unimodal Palindromic Decompositions(DP)
- XMPP 及时通信二
- 2015ACM/ICPC亚洲区长春站 G hdu 5533 Dancing Stars on Me
- 二叉树的遍历
- 软件测试读书列表
- 开发iOS应用要比开发安卓应用省时约30%
- mysql命令操作
- Leetcode138: Partition List
- Leetcode sql算法题
- leetcode-Same Tree
- atomic 加锁操作
- 【转】淘测试---新时代的测试工程师
- java语言写文件内容
- NSNotificationCenter观察者模式