外星人翻译用数字转换模块

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main()
{
	map<string, int> words;    // STL, 建立string到int的映射
	words["zero"]      = 0;
	words["one"]       = 1;
	words["two"]       = 2;
	words["three"]     = 3;
	words["four"]      = 4;
	words["five"]      = 5;
	words["six"]       = 6;
	words["seven"]     = 7;
	words["eight"]     = 8;
	words["nine"]      = 9;
	words["ten"]       = 10;
	words["eleven"]    = 11;
	words["twelve"]    = 12;
	words["thirteen"]  = 13;
	words["fourteen"]  = 14;
	words["fifteen"]   = 15;
	words["sixteen"]   = 16;
	words["seventeen"] = 17;
	words["eighteen"]  = 18;
	words["nineteen"]  = 19;
	words["twenty"]    = 20;
	words["thirty"]    = 30;
	words["forty"]     = 40;
	words["fifty"]     = 50;
	words["sixty"]     = 60;
	words["seventy"]   = 70;
	words["eighty"]    = 80;
	words["ninety"]    = 90;
	words["hundred"]   = 100;
	words["thousand"]  = 1000;
	words["million"]   = 1000000;
	string word[20];
	while(cin >> word[0])
	{
		int totalWord = 1;
		while(cin.peek() != '\n')                         // 看看是不是该换行了
		{
			cin >> word[totalWord++];
		}
		int i, j, negative = 1, m = 0;
		int num[20] = {0};
		for(i = 0; i < totalWord; i++)                 // 转存数值数组
		{
			if(word[i] == "negative")
			{
				negative = -1;
				continue;
			}
			num[m++] = words[word[i]];
		}

		int result = 0;
                // 下面算法的核心在于1, 当一个数比前一个数大的时候,这个数肯定是100, 1000, 或 1000000
                //                 2, 如果已经得到的结果比这个数小的话, 那么一定要把已经得到的结果放大100, 1000, 1000000倍
                //                 3, 如果比这个数大的话,就把前面的数取余的部分放大再加回去
                //                 4, 一些繁琐的小细节
		for(i = 0; i < m; i++)
		{
			{
				if(num[i] > result && result != 0)
					result *= num[i];
				else if(num[i] > result && result == 0)
					result += num[i];
				else
				{
					if(num[i] == 100)
					{
						int t = result % 1000;
						result -= t;
						result += t * 100;
					}
					else if(num [i] == 1000)
					{
						int t = result % 1000000;
						result -= t;
						result += t * 1000;
					}
					else result += num[i];
				}
			}
		}
		result *= negative;
		cout << result << endl;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值