读入两个小于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
题解
思路:
- 转化:每次读入一行字符串,存入数组,得到字符串的长度,遍历数组,将其转化成可计算的式子。当读到 ’ = ’ 时,终止遍历。读到 ’ + ',存入队尾。读到字母时,判断该字母开头的单词表示的数字,将数字入队。
- 计算:当队列非空时,不断读取队首元素,在读到 ’ + ’ 前,将读到的数字 “累加” 记为 ans。读到 ’ + ’ 时,将ans赋给A,ans = 0。每次读取后将队首元素出队,继续循环直到队列为空。A + ans即为结果。
Code
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
queue<char> s;
int main()
{
int len, A, ans;
char a[50];
while(gets(a))
{
A = 0;
ans = 0;
len = strlen(a);
for(int i = 0; i < len; i++)
{
if(a[i] == '=')
break;
else if(a[i] == '+')
{
s.push('+');
i += 1;
}
else if(a[i] == 'z')
{
s.push('0');
i += 4;
}
else if(a[i] == 'o')
{
s.push('1');
i += 3;
}
else if(a[i] == 't' && a[i + 1] == 'w')
{
s.push('2');
i += 3;
}
else if(a[i] == 't' && a[i + 1] == 'h')
{
s.push('3');
i += 5;
}
else if(a[i] == 'f' && a[i + 1] == 'o')
{
s.push('4');
i += 4;
}
else if(a[i] == 'f' && a[i + 1] == 'i')
{
s.push('5');
i += 4;
}
else if(a[i] == 's' && a[i + 1] == 'i')
{
s.push('6');
i += 3;
}
else if(a[i] == 's' && a[i + 1] == 'e')
{
s.push('7');
i += 5;
}
else if(a[i] == 'e')
{
s.push('8');
i += 5;
}
else if(a[i] == 'n')
{
s.push('9');
i += 4;
}
}
while(!s.empty())
{
if(s.front() != '+')
ans = ans * 10 + s.front() - '0';//字符型转化为整型
else
{
A = ans;
ans = 0;
}
s.pop();
}
if(A != 0 || ans != 0)
cout<<A + ans<<endl;
}
return 0;
}