A + B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10595 Accepted Submission(s): 6104
Problem Description
读入两个小于100的正整数A和B,计算A+B.
需要注意的是:A和B的每一位数字由对应的英文单词给出.
需要注意的是:A和B的每一位数字由对应的英文单词给出.
Input
测试输入包含若干测试用例,每个测试用例占一行,格式为"A + B =",相邻两字符串有一个空格间隔.当A和B同时为0时输入结束,相应的结果不要输出.
Output
对每个测试用例输出1行,即A+B的值.
Sample Input
one + two = three four + five six = zero seven + eight nine = zero + zero =
Sample Output
3 90 96
分析:该题是英文的A+B求和,个人思路是用gets函数输入,然后在切割字符串求两数,最后求和:
AC代码:
#include <stdio.h>
#include <string.h>
#define N 100
int main()
{
char s[N],str[N],num[10][8]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int a,b,k,i,j,len,flag,n[5];
while(gets(s))
{
k=1;a=b=0;
for(i=len=0;s[i]!='=';i++)
{
if(s[i]==' ' && len!=0)
{
str[len]='\0';
//printf("%s\n",str);
for(j=0;j<10;j++)
if(strcmp(str,num[j])==0) break;
n[k++]=j;
len=0;
if(s[i+1]=='+') flag=k;
}
else if(s[i]>='a' && s[i]<='z')
{
str[len++]=s[i];
}
}
if(flag==2)
{
a=n[1];
if(k==3)
b=n[2];
else
b=n[2]*10+n[3];
}
else if(flag=3)
{
a=n[1]*10+n[2];
if(k==4)
b=n[3];
else
b=n[3]*10+n[4];
}
//printf("%d %d %d %d,a=%d,b=%d\n",n[1],n[2],n[3],n[4],a,b);
if(a==0 && b==0) break;
else
printf("%d\n",a+b);
}
return 0;
}
下面为网上的其他代码,
代码1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strToInt(char *);
int main()
{
char str[6];
int a, b, c;
while(scanf("%s",str))
{
a = strToInt(str);
while(scanf("%s",str))
{
if(str[0] != '+' && str[0] != '=')
{
b = strToInt(str);
a = a * 10 + b;
}else if(str[0] == '+')
{
c = a;
a = 0;
}else if(str[0] == '=')
{
break;
}
}
if(!a && !c)
{
break;
}else
{
printf("%d\n", a + c);
}
}
return 0;
}
int strToInt(char *str)
{
int num;
if(strcmp(str, "zero") == 0)
{
num = 0;
}else if(strcmp(str, "one") == 0)
{
num = 1;
}else if(strcmp(str, "two") == 0)
{
num = 2;
}else if(strcmp(str, "three") == 0)
{
num = 3;
}else if(strcmp(str, "four") == 0)
{
num = 4;
}else if(strcmp(str, "five") == 0)
{
num = 5;
}else if(strcmp(str, "six") == 0)
{
num = 6;
}else if(strcmp(str, "seven") == 0)
{
num = 7;
}else if(strcmp(str, "eight") == 0)
{
num = 8;
}else if(strcmp(str, "nine") == 0)
{
num = 9;
}
return num;
}
该方法是处理含空格字符串的一种处理方法,过程是用scanf函数分段输入处理,很值得学习和借鉴。
未完待续...