您的位置:首页 > 其它

Leetcode Multiply Strings

2014-06-29 16:14 489 查看
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.

class Solution {
public:
string multiply(string num1, string num2) {
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
if(num1.length() < num2.length()) swap(num1,num2);
string sum(num1.length()+num1.length()+1,'0');
for(int i = 0 ;i < num2.length(); ++ i){
int carry = 0;
for(int j = 0 ; j < num1.length(); ++ j){
int tmp = (num1[j]-'0')*(num2[i]-'0')+carry;
carry = tmp/10;
tmp = tmp%10+(sum[i+j]-'0');
sum[i+j] ='0'+tmp%10;
sum[i+j+1] = '0'+(sum[i+j+1]-'0' + tmp/10);
}
if(carry != 0){
int num = carry+(sum[i+num1.length()]-'0');
sum[i+num1.length()] = '0'+num%10;
if(num/10) sum[i+num1.length()+1] = '0'+(sum[i+num1.length()+1]-'0'+num/10);
}
}
reverse(sum.begin(),sum.end());
int index = 0;
for(index = 0 ; index < sum.length(); ++ index){
if(sum[index]!='0') return string(sum.begin()+index, sum.end());
}
if(index == sum.length()) return "0";
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: