HDU - 1228 A + B【C++,map題解】

原題鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1228

A + B

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21350    Accepted Submission(s): 12777

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
 

題記:

    本題使用了STL中的map,把string類型的數字轉化爲對應int型的數字,然後進行計算。

    map的使用非常簡單,話不多說,直接看代碼吧。

C++代碼:

#include <iostream>
#include <map> 
#include <cstring>
using namespace std;
 
int main(){
    map<string, int> num;
    num["zero"] = 0;
    num["one"] = 1;
    num["two"] = 2;
    num["three"] = 3;
    num["four"] = 4;
    num["five"] = 5;
    num["six"] = 6;
    num["seven"] = 7;
    num["eight"] = 8;
    num["nine"] = 9;
    
    int a, b;
    string s;
    
    for( ; ; ) {
        a = 0;  //a存放+號前的數
        while(cin >> s) {
            if(s=="+"){
            	break;
			}  
            a = a * 10 + num[s];
        }
        
        b = 0;  //b存放+號後的數
        while(cin >> s) {
            if(s == "="){
            	 break;
			} 
            b = b * 10 + num[s];
        }
        
        if(a == 0 && b == 0){
        	break;
		}else{
        	cout << a + b << endl;
		} 
    }
    
    return 0;
}

 

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