LeetCode-Integer to English Words-解题报告

本文介绍了一种将非负整数转换为其英文单词表示的方法。通过逐三位处理的方式,确保了转换过程的高效与准确。文章提供了一个具体的C++实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接 https://leetcode.com/problems/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"

每3位做一次处理


class Solution {
public:
	string numberToWords(int num) {
		if (num == 0)return Oto19[0];
		string res = "";
		int pos = 9;
		bool flag = false;
		int tmp = num % 1000;
		num /= 1000;
		per3ToWord(tmp);
		while (num)
		{
			tmp = num % 1000;
			num /= 1000;
			if (tmp)
				ans.push_front(zoTo[pos]);
			pos++;
			per3ToWord(tmp);
		}
		for (auto& item : ans)
		{
			if (!flag)flag = true;
			else res += " ";
			res += item;
		}
		return res;
	}
	void per3ToWord(int num)
	{
		int a = num / 100;
		num %= 100;
		int b = num / 10;
		num %= 10;
		int c = num;
		if (b > 1)
		{
			if (c)
				ans.push_front(Oto19[c]);
			ans.push_front(zoTo[b - 2]);
		}
		else if (b != 0 || c != 0)
		{
			ans.push_front(Oto19[b*10 + c]);
		}
		if (a)
		{
			ans.push_front("Hundred");
			ans.push_front(Oto19[a]);
		}
		return;
	}
private:
	static string Oto19[20];
	static string zoTo[12];
	deque<string> ans;
};
string Solution::Oto19[20] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
string Solution::zoTo[12] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred", "Thousand", "Million", "Billion" };


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值