LeetCode Integer to English Words

本文介绍了一种将非负整数转换为其英文单词表示的方法,适用于小于2^31 - 1的整数。通过实例展示了如何将数字如123、12345和1234567等转换为对应的英文描述。

Description:

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"

Solution:

前面没有打这道题目是有点搞不清and应该怎么用,但是刚刚发现竟然不需要写and,难度系数瞬间下降。小模拟。



<span style="font-size:18px;">public class Solution {
	public String numberToWords(int num) {
		String ans = "";

		int tot = 0;
		String[] digit = { "", " Thousand", " Million", " Billion" };
		while (num > 0) {
			if (num % 1000 > 0)
				ans = turnToHundred(num % 1000) + digit[tot] + " " + ans;
			tot++;
			num = num / 1000;
		}

		ans = ans.trim();

		if (ans.equals(""))
			ans = "Zero";

		return ans;
	}

	String[] ones = { "", "One", "Two", "Three", "Four", "Five", "Six",
			"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
			"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
			"Nineteen" };
	String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
			"Seventy", "Eighty", "Ninety" };

	public String turnToHundred(int num) {
		String ans = "";
		int one = num % 10;
		int ten = num % 100;
		int hundred = num / 100;
		if (hundred > 0)
			ans = ones[hundred] + " Hundred ";
		if (ten < 20)
			ans = ans + ones[ten];
		else
			ans = ans + tens[ten / 10] + " " + ones[one];
		ans = ans.trim();

		return ans;
	}
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值