九度OJ 1010 A+B

題目鏈接:http://ac.jobdu.com/problem.php?pid=1010


題目分析:

先寫一個函數將輸入的數字單詞轉化爲對應的數字,在計算值的時候調用該函數。

主要的算法在於對於輸入字符串的邏輯判斷,即:輸入幾個數字單詞,什麼時候打印值。

我的設計思想是:首先讀入一個數字單詞,然後讀入下一個輸入的字符串(中間判斷空格在這裏就不說了),判斷先一個字符串是加號還是數字單詞。是加號的話,繼續輸入字符串,那麼這個必然是數字單詞,再繼續輸入,判斷是等於號還是數字單詞,這裏兩種情況結果就都可以輸出了;第一個數字單詞之後如果依然是數字單詞的話,那麼繼續輸入,必然是加號,在進行上面加號之後的判斷,依然有兩種情況的輸出。最後再判別一下都是0的退出情況。


源代碼:

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;

int toInteger(string A)
{
	if(A=="one")
		return 1;
	else if(A=="two")
		return 2;
	else if(A=="three")
		return 3;
	else if(A=="four")
		return 4;
	else if(A=="five")
		return 5;
	else if(A=="six")
		return 6;
	else if(A=="seven")
		return 7;
	else if(A=="eight")
		return 8;
	else if(A=="nine")
		return 9;
	else if(A=="zero")
		return 0;
	else
		return -1;
}

int main()
{
	string A1,A2,B1,B2,t1,t2;
	int num1,num2,sum;
	while (cin>>A1)
	{
		num1 = toInteger(A1);
		char c;
		c = getchar();
		if (c == ' ')
		{
			cin>>t1;
			if (t1[0] == '+')	//判斷第二個輸入字符串爲+
			{
				c = getchar();
				if (c == ' ')
				{
					cin >> B1;	//輸入第三個字符串數字單詞
					num2 = toInteger(B1);
					c = getchar();
					if (c == ' ')
					{
						cin>>t2;
						if (t2[0] == '=')	//判斷最後輸入的字符串爲=
						{
							if (num1 == 0 && num2 == 0)
							{
								break;
							}
							else
							{
								cout<<num1 + num2<<endl;
							}
						}
						else	//不是=,爲數字單詞
						{
							num2 = num2 * 10 + toInteger(t2);
							cout<<num1 + num2<<endl;
						}
					}
				}
			}
			else	//第一個數字單詞之後不爲+,則爲另一個數字單詞
			{
				num1 = num1 * 10 + toInteger(t1);

				c = getchar();
				if (c == ' ')
				{
					cin >> t1;	//輸入加號
					c = getchar();
					if (c == ' ')
					{
						cin >> B1;	//輸入第三個字符串數字單詞
						num2 = toInteger(B1);
						c = getchar();
						if (c == ' ')
						{
							cin>>t2;
							if (t2[0] == '=')	//判斷最後輸入的字符串爲=
							{
								cout<<num1 + num2<<endl;
							}
							else	//不是=,爲數字單詞
							{
								num2 = num2 * 10 + toInteger(t2);
								cout<<num1 + num2<<endl;
							}
						}
					}
				}
			}
		}
	}
	return 0;
}


發佈了67 篇原創文章 · 獲贊 18 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章