九度OJ 1010 A +B

 1 #include <iostream>
 2 #include <string>
 3 #include <sstream>
 4 using namespace std;
 5 
 6 int strToInt(string strA)
 7 {
 8 
 9     if(strA=="zero")
10                     {
11 
12                         return 0;
13                     }
14                 else if(strA == "one")
15                 {
16                     return 1;
17                 }
18                 else if(strA == "two")
19                 {
20                     return 2;
21                 }
22                 else if(strA == "three")
23                 {
24                     return 3;
25                 }
26                 else if(strA == "four")
27                 {
28                    return 4;
29                 }
30                 else if(strA == "five")
31                 {
32                     return 5;
33                 }
34                 else if(strA == "six")
35                 {
36                    return 6;
37                 }
38                 else if(strA == "seven")
39                 {
40                     return 7;
41                 }
42                 else if(strA == "eight")
43                 {
44                     return 8;
45                 }
46                 else if(strA == "nine")
47                 {
48                     return 9;
49                 }
50                 //else if(strA == "+")
51 
52 }
53 int main()
54 {
55     string str;
56     int a = 0;
57     int b = 0;
58     while(cin>>str)
59     {
60         //if(str == "zero + zero")
61         string strA,strB;
62 
63         if(str != "+" && str!= "=")
64             a = strToInt(str)+10*a;
65         else if(str == "+")
66             {
67                 b = a;
68                 a = 0;
69             }
70             else if(str == "=")
71             {
72                 if(a==0 && b==0)
73                     return 1;
74                 cout<<a+b<<endl;
75                 a = b = 0;
76             }
77     }
78 
79 
80     return 0;
81 }

解题思路:首先是归为字符串的处理问题,从流中接受字符串,cin>>str的特性是接受直到遇到空格或者回车,题中正好每个单词之间有空格,接受到的单词根据strToInt(..)转换成整数,若还没遇到+,表示后续还有数字,应该将原数字乘以10再加上所遇到的数字,遇到+则表示加数A已经计算完毕,保存,继续计算b,直到遇到=,计算a+b

posted @ 2014-11-23 17:34  ElephantKing  阅读(196)  评论(2编辑  收藏  举报