LuoguP2108 学英语 题解

Content

给出整数 \(x\) 的英文写法,求出这个整数 \(x\)

规则详见题面

数据范围:\(|x|\leqslant 999999999\)\(9\)\(9\))。

Solution

题目思路很简单,但要注意细节。

开两个变量 \(ans\)(最终的答案) 和 \(now\)(当前的计数),边输入一个字符串边一个一个计数,至于对应的操作吗——

  1. 如果这个字符串是 \(\texttt{thousand}\) 或者 \(\texttt{million}\) 的话,就直接将 \(now\) 全部计入 \(ans\) 里面,并将 \(now\) 清空。

  2. 否则,将读取到的字符串对应的数字加入到 \(now\) 当中(如果是 \(\texttt{hundred}\) 就将 \(now\) 乘上 \(100\))。

  3. 注意 \(\texttt{negative}\) 的情况,此时应该在最后输出负数。

具体的思路就是这些。

Code

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <iostream> 
using namespace std;

string s;
long long num, now, f;

int main() {
	f = 1;
	while(cin >> s) {
		if(s == "negative")	f = -1;
		if(s == "one")		now++;
		if(s == "two") 	now += 2;
		if(s == "three")	now += 3;
		if(s == "four")	now += 4;
		if(s == "five")	now += 5;
		if(s == "six")		now += 6;
		if(s == "seven")	now += 7;
		if(s == "eight")	now += 8;
		if(s == "nine")	now += 9;
		if(s == "ten")		now += 10;
		if(s == "eleven")	now += 11;
		if(s == "twelve")	now += 12;
		if(s == "thirteen")	now += 13;
		if(s == "fourteen")	now += 14;
		if(s == "fifteen")	now += 15;
		if(s == "sixteen")	now += 16;
		if(s == "seventeen")	now += 17;
		if(s == "eighteen")	now += 18;
		if(s == "nineteen")	now += 19;
		if(s == "twenty")	now += 20;
		if(s == "thirty")	now += 30;
		if(s == "forty")	now += 40;
		if(s == "fifty")	now += 50;
		if(s == "sixty")	now += 60;
		if(s == "seventy")	now += 70;
		if(s == "eighty")	now += 80;
		if(s == "ninety")	now += 90;
		if(s == "hundred")	now *= 100;
		if(s == "thousand")	num += now * 1000, now = 0;
		if(s == "million")	num += now * 1000000, now = 0;
	}
	num += now;
	printf("%lld", num * f);
}

Supplement

建议做完这道题目的读者去做一下【P1617】爱与愁的一千个伤心的理由,大意就是将阿拉伯数字转为英文读法。

顺便推广一下我在这道题的题解

posted @ 2021-12-21 21:07  Eason_AC  阅读(57)  评论(0)    收藏  举报