Facebook Interview - Integer to English Phrase

Given an integer between 0 and 999,999, print an English phrase that describes the integer (eg, “One Thousand, Two Hundred and Thirty Four”)

 

http://ideone.com/Q1AT1p

vector<string> under20 = {"Zero", "One", "Two", "Three", "Four", "Five", 
		"Six", "Seven", "Eight", "Nine", "Ten",
		"Eleven","Twelve", "Thirteen", "Fourteen", "Fifteen",
		"Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"};
 
vector<string> tens = {"Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", 
		"Sixty", "Seventy", "Eighty", "Ninety"};

string numBelow1000(int num) {
	if(num == 0) return under20[0];
	string ret = "";
	if (num > 100) {
		ret = under20[num/100] + " Hundred";
		num %= 100;
		if (num == 0) {
			return ret;
		} else {
			ret += " and ";
		} 
	}
	
	if (num <= 20) {
		ret += under20[num];
	} else {
		ret += tens[num/10];
		num %= 10;
		if (num > 0)
			ret += " " + under20[num];
	}
	return ret;
}

string num2string(int num) {
	int part1 = num / 1000;
	int part2 = num % 1000;
	string res;
	if(part1) {
		res = numBelow1000(part1) + " Thousand";
		if(part2) res += ", " + numBelow1000(part2);
	} else {
		res = numBelow1000(part2);
	}
	return res;
}

 

 

你可能感兴趣的:(interview)