`
jgsj
  • 浏览: 957003 次
文章分类
社区版块
存档分类
最新评论

面试题: 数字转英文 数字发音

 
阅读更多

给定一个数字,转换成英文,如:123 one hundred twenty three

本题的逻辑并不是很难,但是很麻烦,分情况很多,要想很优雅地解决这个问题确实是不容易的事情。因为逐个数字地翻译,那程序就会变得非常丑陋。

所以必须很好地把数字分段,然后优雅地组合在一起,考虑好扩展性。

下面设计一个类,看看如何实现,这个程序可以支持长整型,而且扩展性非常好,可以很容易地扩展。

下面看看测试效果是怎么样的:

#include<iostream>
#include"PronounceNum.h"

using namespace std;

int main() 
{
	PronounceNum pronounce;
	
	cout<<pronounce(12223359855649546465)<<endl;

	cout<<pronounce(5465498465456465)<<endl;

	system("pause");
	return 0;
}

可以支持很长的数字了。

下面是类的定义:

#pragma once
#include<string>
#include<vector>

class PronounceNum
{
public:
	PronounceNum();
	~PronounceNum();

	std::vector<std::string> digits;
	std::vector<std::string> teens;
	std::vector<std::string> tens;
	std::vector<std::string> bigs;

	std::string numToString(long long num);
	std::string numUnder100(int num);
	std::string operator()(long long num);
	
private:

};

下面是类的实现:

1 定义英文单词

#include"PronounceNum.h"

PronounceNum::PronounceNum() { std::string dig[9] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; digits.assign(dig, dig+9);

std::string tee[9] = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; teens.assign(tee, tee+9);

std::string ten[9] = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; tens.assign(ten, ten+9);

//扩展这个big,就可以实现无穷大数字发音了。只要你知道这个数字英文如何发音的话。 std::string big[] = {"", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Sextillion", "Septillion", "Octillion", "Nonillion"}; int biglen = sizeof(big)/sizeof(std::string); bigs.assign(big, big+biglen); }

这里的big字符串就是可扩展的位置。

2 主要的函数

std::string PronounceNum::numToString(long long num)
{
	//Special cases
	if(num == 0) return "Zero";
	else if(num == LLONG_MIN) return "Minimum Long Long integer!";
	else if(num < 0) return "Negative" + numToString(-1*num);

	int count = 0;
	std::string str = "";

	while (num > 0)
	{
		if (num % 1000 != 0)
		{
			//这句是最重要的一句,1000的发音就在这里处理。
			//前面+一个函数处理100一下的数字
			//利用字符串数组bigs轻松处理每个1000的发音
			//而且巧妙地在第一个位置加上""空字符串。
			str = numUnder100(num % 1000) + bigs[count] + " " + str;
		}
		num /= 1000;
		count++;
	}
	return str;
}


注释了最重要的一句。这个程序的精华所在了。

3 处理100以下的数字:

std::string PronounceNum::numUnder100(int num)
{
	std::string str = "";

	//100以下的数字需要四种情况处理,十分麻烦。
	if (num >= 100)
	{
		str += digits[num/100-1] + " Hundred ";
		num %= 100;
	}
	if (num >= 11 && num <= 19)
	{
		return str + teens[num - 11] + " ";
	}
	else if (num == 10 || num >= 20)
	{
		str += tens[num/10 - 1] + " ";
		num %= 10;
	}
	if (num >= 1 && num <= 9)
	{
		str += digits[num - 1] + " ";
	}
	return str;
}

之所以这个题目难就是因为分的情况太多了

4 定义一个括号()的操作:

std::string PronounceNum::operator()(long long num)
{
	return numToString(num);
}

可以方便地直接使用对象名发音了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics