leetcode 273. Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

这题纯粹考细心,其他没什么说的


const string onedigit[9] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
const string teensless20[10] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
const string teens[8] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

class Solution {
	string get_digit(int num)
	{
		return onedigit[num-1];
	}
	string get_teens(int num)
	{
		if (num < 20)
			return teensless20[num - 10];
		return teens[num / 10 - 2];
	}
	string get_hundred(int num)
	{
		string re;
		if (num >= 100)
			re += get_digit(num / 100) + " Hundred ";
		if (num - num / 100 * 100>=10)
			re +=get_teens(num - num / 100 * 100)+" ";
		if (num % 10 != 0 && (num - num / 100 * 100 >= 20 || num - num / 100 * 100<10))
			re += get_digit(num % 10);
		while (re.back() == ' ')
			re.pop_back();
		return re;
	}
public:
	string numberToWords(int num) {//0-2 147 483 647
		if (num == 0)
			return "Zero";
		string re;
		vector<int>digits;
		while (num != 0)
		{
			digits.push_back(num % 10);
			num /= 10;
		}
		if (digits.size() > 9)
			re += get_digit(digits[9])+" Billion ";
		if (digits.size() > 6)
		{
			int jmax = digits.size() >= 9 ? 8 : digits.size()-1;
			int sum = 0;
			for (int j = jmax; j >= 6; j--)
				sum = 10 * sum + digits[j];
			if (sum>0)
			re += get_hundred(sum)+" Million ";
		}
		if (digits.size() > 3)
		{
			int jmax = digits.size() >= 6 ? 5 : digits.size()-1;
			int sum = 0;
			for (int j = jmax; j >= 3; j--)
				sum = 10 * sum + digits[j];
			if (sum>0)
			re += get_hundred(sum) + " Thousand ";
		}
		int jmax = digits.size() >= 3 ? 2 : digits.size()-1;
		int sum = 0;
		for (int j = jmax; j >= 0; j--)
			sum = 10 * sum + digits[j];
		if (sum>0)
		re += get_hundred(sum);
		while (re.back() == ' ')
			re.pop_back();
		return re;
	}
};


accepted



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值