Multiply Strings ---leetcode
发布时间:2021-02-24 20:46:36 所属栏目:大数据 来源:网络整理
导读: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 inter
|
Given two numbers represented as strings,return multiplication of the numbers as a string. Note:
Subscribe?to see which companies asked this question 这是来自于leetcode上的一道算法题目。 算法思路:用char存储大数的每一位,然后控制每一位之间的相乘和进位即可。 我的代码如下: class Solution {
public:
string multiply(string num1,string num2) {
const char *ch1 = num1.c_str();
const char *ch2 = num2.c_str();
const unsigned int l1=num1.length();
const unsigned int l2=num2.length();
const unsigned int lc = l1 +l2 +1;
//cout<<str1.length()+str2.length()+1<<endl;
char *ch3 = (char *)malloc((lc+1)*sizeof(char));
for (int i = 0; i < lc; i++)
{
ch3[i]='0';
}
for (int i = l1 - 1; i >= 0 ; i--)
{
unsigned int start = (l1-i);
int re = 0;
for (int j = l2 - 1; j >= 0 ; j--)
{
int temp = (ch1[i]-48)*(ch2[j]-48) + re;
int result = ch3[lc - (l1-i)-(l2-j)]+(temp%10) -48;
re =temp/10;
if (result>9)
{
re+=result/10;
result=result%10;
}
ch3[lc - (l1-i)-(l2-j)]= result+48;
if (j==0)
{
ch3[lc - (l1-i)-(l2-j)-1]=re+48;
}
}
}
string a(ch3);
free(ch3);
int i=0;
for(;i<lc-2;i++){
if(a.substr(i,1)=="0")continue;
else break;
}
return a.substr(i,lc-i-1);
}
};结果:
(编辑:邯郸站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |



