题目描述:
请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回error
输入描述:
输入为一行,包含两个字符串,字符串的长度在[1,100]。
输出描述:
输出为一行。合法情况输出相加结果,非法情况输出error
示例1
输入
123 123
abd 123
输出
246
error
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MIN(x, y) ((x) < (y) ? (x) : (y))
char Error(char c)
{
if(c > '9' || c < '0')
{
return 0;
}
return 1;
}
int main()
{
char str[102] = { 0 }; //存储处理后的字符串
char str0[210] = { 0 };
char str1[101] = { 0 };
char str2[101] = { 0 };
char *p = NULL;
int len1, len2, min, CY = 0;
int i, value = 0, flag = 0;
while (gets(str0))
{
p = strchr(str0, ' ');
strncpy(str1, str0, p - str0);
strcpy(str2, p + 1);
p = str1;
while(*p != NULL) //遍历处理非0~9的字符
{
if(Error(*p) == 0)
{
printf("error\n");
flag = 1;
break; //跳出while(*p != NULL) 循环
}
p++;
}
if(flag)
{
flag = 0;
continue; //跳出本次while (gets(str0)) 循环
}
p = str2;
while(*p != NULL)
{
if(Error(*p) == 0)
{
printf("error\n");
flag = 1;
break;
}
p++;
}
if(flag)
{
flag = 0;
continue;
}
len1 = strlen(str1);
len2 = strlen(str2);
min = MIN(len1, len2);
memset(str, 0, sizeof(str) / sizeof(*str));
CY = 0; // 将进位标志置为 0
for (i = 0; i < min; i++) // 从后往前处理
{
value = str1[len1 - i - 1] - '0' + str2[len2 - i - 1] - '0' + CY;
if (value >= 10)
{
str[i] = value - 10 + '0';
CY = 1; // 进位
}
else
{
str[i] = value + '0';
CY = 0;
}
}
if (len1 == len2) //两字符串长度相等,且还有进位1
{
if (CY == 1)
str[i++] = '1';
}
else if (len1 > len2) //处理其中较长字符串剩余的长度
{
while (i < len1)
{
while (CY == 1 && str1[len1 - i - 1] == '9')//进位标志位为1,且后续的字符为'9'
{
str[i] = '0';
if (len1 - i - 1 == 0) //最后一个字符为'9',且还有进位1
str[++i] = '1'; //则增加一个字节,置为'1'
i++;
continue;
}
if (str1[len1 - i - 1] != '9' && len1 - i - 1 >= 0)
{
str[i++] = str1[len1 - i - 1] + CY;//第一次当str1[len1 - i - 1] != '9'时,有可能还有进位,所以得加上CY
CY = 0;
}
}
}
else if(len1 < len2)
{
while (i < len2)
{
while (CY == 1 && str2[len2 - i - 1] == '9')
{
str[i] = '0';
if (len2 - i - 1 == 0)
str[++i] = '1';
i++;
continue;
}
if (str2[len2 - i - 1] != '9' && len2 - i - 1 >= 0)
{
str[i++] = str2[len2 - i - 1] + CY;
CY = 0;
}
}
}
for (int j = i - 1; j >= 0; j--)
printf("%c", str[j]);
printf("\n");
}
return 0;
}