A + B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8165 Accepted Submission(s): 4603
Problem Description
读入两个小于100的正整数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
Source
Recommend
JGShining
解题思路:
首先定义一个二维字符数组,存十个单词,以作比较。然后用一个字符串接收整个计算公式。接下来将字符串分解,逐一转换成整数相加,最后判断是否为0,进行输出。注意空格的判断以及加号的判断。为了方便可以将最后一个单词后去掉,不作处理。
解题代码:
#include<stdio.h>
#include<string.h>
char Num[10][6]={"zero","one","two","three","four","five","six","seven","eight","nine"};
char strt[5];
int NumS(char strt[]) {
int i,j,x=0;
for(i=0;i<10;i++) {
j=strcmp(strt,Num[i]);
x++;
if(j==0) return --x;
}
return 0;
}
int main() {
int i,j,m,n,s,Sum,q;
char str[30];
while(gets(str)) {
m=q=Sum=i=0;
n=1;
while(n--) {
s=1;
memset(strt,'\0',5);
for(i;i<strlen(str)-2;i++) {
if(str[i]==32) {
m=0;
n+=1;
if(str[i+1]!=43)
s=10;
if(str[i+1]==43&&str[i+2]==32) {
i+=2;
}
i++;
break;
}
strt[m]=str[i];
m++;
}
j=NumS(strt);
Sum+=j*s;
}
if(Sum>0)
printf("%d\n",Sum);
else
break;
memset(str,'\0',strlen(str));
}
return 0;
}
以下是改良版:
#include<stdio.h>
#include<string.h>
char Num[10][6]={"zero","one","two","three","four","five","six","seven","eight","nine"};
char strt[5];
int NumS(char strt[]) {
int i,j,x=0;
for(i=0;i<10;i++) {
j=strcmp(strt,Num[i]);
x++;
if(j==0) return --x;
}
return 0;
}
int main() {
int i,j,m,n,s,Sum,q;
char str[30];
while(gets(str)) {
m=q=Sum=i=0;
n=1;
while(n--) {
s=1;
memset(strt,'\0',5);
for(i;i<strlen(str)-2;i++) {
if(str[i]==32) {
m=0;
n+=1;
if(str[i+1]!=43)
s=10;
if(str[i+1]==43&&str[i+2]==32) {
i+=2;
}
i++;
break;
}
strt[m]=str[i];
m++;
}
j=NumS(strt);
Sum+=j*s;
}
if(Sum>0)
printf("%d\n",Sum);
else
break;
memset(str,'\0',strlen(str));
}
return 0;
}