說起這道題,我其實(shí)是很氣的,個(gè)人賽最后兩個(gè)小時(shí)我一道題都沒做出來,這道題其實(shí)很好做,做的時(shí)候總怕有什么坑,但其實(shí)差不多思路理順寫下來就行了。還是怪自己代碼力弱,前面的卡了一下,做的時(shí)候就不是很順,這道題和k題不是很敢下手,但其實(shí)都是能做的。
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<string>
#include<map>
#include<iostream>
using namespace std;
map<string,int> mp;
int main()
{
int t;
mp.clear();
mp["one"] = 1;
mp["two"] = 2;
mp["three"] = 3;
mp["four"] = 4;
mp["five"] = 5;
mp["six"] = 6;
mp["seven"] = 7;
mp["eight"] = 8;
mp["nine"] = 9;
mp["ten"] = 10;
mp["eleven"] = 11;
mp["twelve"] =12;
mp["thirteen"] =13;
mp["fourteen"] =14;
mp["fifteen"] =15;
mp["sixteen"] =16;
mp["seventeen"] =17;
mp["eighteen" ] =18;
mp["nineteen"] = 19;
mp["twenty"] = 20;
mp["thirty"] = 30;
mp["forty"] = 40;
mp["fifty"] = 50;
mp["sixty"] = 60;
mp["seventy"] = 70;
mp["eighty"] = 80;
mp["ninety"] = 90;
scanf("%d",&t);
while(t--)
{
string tmp;
char c =' ';
int ans = 0,x=0;
while(c!='\n')
{
cin>>tmp;
c = getchar();
if(tmp == "million")
{
ans+=x*1000000;
x =0;
}
else if(tmp == "thousand")
{
ans += x*1000;
x =0;
}
else if(tmp == "hundred")
{
x*=100;
}
else if(tmp == "and")
{
continue;
}
else
{
x +=mp[tmp];
//printf("***%d***\n",x);
}
//cout<<tmp<<endl;
}
ans +=x;
printf("%d\n",ans);
}
}
這段代碼有幾個(gè)很妙的處理技巧,1: 輸入時(shí)候可以不用gets()讀取包括空格在內(nèi)的字符,可以通過巧用getchar()吸收scanf緩沖區(qū)的字符來判斷輸入是否結(jié)束,當(dāng)然有一點(diǎn)很重要char c = ‘ ’,要初始化為一個(gè)空格,不然char型默認(rèn)用0填充,根本進(jìn)入不了循環(huán)。2 : 還有就是巧用map來實(shí)現(xiàn)字符的轉(zhuǎn)換。
我承認(rèn)在字符串處理這塊我還是很弱的啊,做的題少,接觸的少,很多技巧思路,比賽的時(shí)候一時(shí)半會(huì)想不到;