A + B problem
Time Limit: 1000MS Memory limit: 65536K
题目描述
Given two integers a and b(0
≤
a, b <100), your task is to calculate the result of a+b. Please note that the two integers a and b is described by English words, see the sample input and sample output for details.
输入
There are several test cases(less than 100).
For each test case:
Only one line contains one string with the format of “a + b =”.
Input ends with a==0 and b==0.
输出
For each test case, output the result in one line.
示例输入
one + one = three four + five six = zero + zero =
示例输出
2 90
提示
来源
qinchuan
我最近处理字符串有个总体倾向:分段处理,处理完一段即刻删除。不知这样好不好,好像过分依赖string.erase函数了,不过话说回来,这个函数还真是个神器呢。
思路:题中说这两个数(0≤ a, b <100),所以它们只有可能是一位数或者两位数。那么这个字符串(算式)就只可能有四种情况(先设加数两位a1,a2,被加数b1,b2):
1、a1空格+空格b1空格=(两个数都只有个位)
2、a1空格a2空格+空格b1空格=(加数有十位,被加数只有个位)
3、a1空格+空格b1空格b2空格=(加数只有个位,被加数有十位)
4、a1空格a2空格+空格b1空格b2空格=(都是十位)
示例程序
#include <stdio.h>
#include <string>
#include <iostream>
#include <string.h>//基本思路:找串中字符个数确定格式,按规律处理数
using namespace std;
int chuli(string c)//函数里擦不去
{
switch (c[0])
{
case 111:
return 1;
case 116:
if (c[1]==119)return 2;
else return 3;
case 102:
if (c[1]==111)
return 4;
else return 5;
case 115:
if (c[1]==105)
return 6;
else return 7;
case 101:
return 8;
case 110:
return 9;
case 122:
return 0;
}
}
int f(string c)
{
int sum=0;
for (int i=0;i<c.size();i++)
{
sum+=(c[i]==' '&&1);
}
return sum;
}
int main()
{
string c;
int a1,a2,b1,b2;
//char c1[15],c2[15],c3[15],c4[15],c5[15],c6[15]; c1c2+c4c5=
while (getline(cin,c,'\n'))
{
if (c[0]=='z'&&c[7]=='z')break;
switch (a1=chuli(c))
{
case 1:
case 2:
case 6:
c.erase(0,4);
break;
case 4:
case 5:
case 9:
case 0:
c.erase(0,5);
break;
case 3:
case 7:
case 8:
c.erase(0,6);
break;
}
//cout<<f(c)<<"$$$***$$$"<<endl;
switch (f(c))
{
case 2:
c.erase(0,2);
cout<<a1+chuli(c)<<endl;
break;
case 3:
if (c[0]=='+')
{
c.erase(0,2);
switch (b1=chuli(c))
{
case 1:
case 2:
case 6:
c.erase(0,4);
break;
case 4:
case 5:
case 9:
case 0:
c.erase(0,5);
break;
case 3:
case 7:
case 8:
c.erase(0,6);
break;
}
b2=chuli(c);
cout<<10*b1+a1+b2<<endl;
}
else
{
switch (a2=chuli(c))
{
case 1:
case 2:
case 6:
c.erase(0,4);
break;
case 4:
case 5:
case 9:
case 0:
c.erase(0,5);
break;
case 3:
case 7:
case 8:
c.erase(0,6);
break;
}
c.erase(0,2);
b1=chuli(c);
cout<<10*a1+b1+a2<<endl;
}
break;
case 4:
switch (a2=chuli(c))
{
case 1:
case 2:
case 6:
c.erase(0,4);
break;
case 4:
case 5:
case 9:
case 0:
c.erase(0,5);
break;
case 3:
case 7:
case 8:
c.erase(0,6);
break;
}
c.erase(0,2);
switch (b1=chuli(c))
{
case 1:
case 2:
case 6:
c.erase(0,4);
break;
case 4:
case 5:
case 9:
case 0:
c.erase(0,5);
break;
case 3:
case 7:
case 8:
c.erase(0,6);
break;
}
b2=chuli(c);
cout<<10*(a1+b1)+a2+b2<<endl;
break;
};
//cout<<f(c)<<endl;
//printf("%s\n%s\n",c1,c2);
}
return 0;
}
PS:长了点,主要是case太多,每个都要在外面判断,string类在函数调用时传进去的是一个复制品,用string.erase擦除不管用,只能在外面擦,所以费了很多事。方法虽麻烦,但贵在是自己的,从思路到代码实现,毫无借鉴/参考/剽窃。如有大神有更好的方法,请不吝赐教,拜谢!