原题:
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路:加就好了。。。
char* addStrings(char* num1, char* num2) {
char* result;
result=(char*)malloc(sizeof(char)*5102);
int len1=strlen(num1);
int len2=strlen(num2);
int flag=0;
int n,m,k;
for(n=len1-1,m=len2-1,k=5100;n>=0&&m>=0;n--,m--,k--)
{
if(flag+*(num1+n)+*(num2+m)-96>=10)
{
*(result+k)=flag+*(num1+n)+*(num2+m)-96+48-10;
flag=1;
}
else
{
*(result+k)=flag+*(num1+n)+*(num2+m)-96+48;
flag=0;
}
}
if(m<0&&n>=0)
{
for(int l=n;n>=0;n--,k--)
{
if(flag+*(num1+n)-48>=10)
{
*(result+k)=flag+*(num1+n)-10;
}
else
{
*(result+k)=flag+*(num1+n);
flag=0;
}
}
}
else if(n<0&&m>=0)
{
for(int l=m;m>=0;m--,k--)
{
if(flag+*(num2+m)-48>=10)
{
*(result+k)=flag+*(num2+m)-10;
}
else
{
*(result+k)=flag+*(num2+m);
flag=0;
}
}
}
else
{
}
if(flag==1)
{
*(result+k)='1';
result=result+k;
}
else
{
result=result+k+1;
}
return result;
}