知识点:
1.字符串翻转
2.对字符数组对应操作
3.字符和数字转换
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*字符翻转*/
void reverse(char *s)
{
int i;
int len;
char tmp;
len = strlen(s);
for (i = 0; i <len/2; i++)
{
tmp = s[i];
s[i] = s[len-1-i];
s[len-1-i] = tmp;
}
}
/************************************************************************/
//addone:加数
//addtwo:被加数
//added:保存的是这两个数的和
/************************************************************************/
void stradd(char *added, char *addone, char *addtwo)
{
int lenone,lentwo,i,small,num;
int flag = 0;
lenone = strlen(addone);
lentwo = strlen(addtwo);
small = (lenone <= lentwo) ? lenone : lentwo;
reverse(addtwo);
reverse(addone);
for (i = 0; i < small; i++)
{
num = addone[i] - '0' + addtwo[i] - '0' + flag;
if (num > 9)
{
num = num %10;
flag = 1;
}
else
flag = 0;
added[i] = num + '0';
}
if (lenone < lentwo)
{
for (i = small; i < lentwo; i++)
{
num = addtwo[i] - '0' + flag;
if (num >9)
{
num = num - 10;
flag = 1;
}
else
flag = 0;
added[i] = num +'0';
}
}
if (lenone > lentwo)
{
for (i = small; i < lenone; i++)
{
num = addone[i] - '0' + flag;
if (num >9)
{
num = num - 10;
flag = 1;
}
else
flag = 0;
added[i] = num +'0';
}
}
if(lenone == lentwo)
{
if (flag){
added[i] = flag + '0';
i++;
}
}
added[i] = '\0';
reverse(added);
// printf( "%s\n", added);
}
int main(void)
{
char str[] = "123456";
char str1[] = "876";
char s1[] = "138999129837281929381892";
char s2[] = "121212123172837184345";
char result[100];
stradd(result, s1, s2);
printf( "%s\n", result );
/*reverse(str);
printf("%s\n",str);*/
return 0;
}
vc上运行结果:
139120341960454766566237
Press any key to continue