首页 > 代码库 > Leetcode Multiply Strings
Leetcode 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.
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"; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。