作者:鹏城飞将 | 来源:互联网 | 2024-12-24 16:53
目录
问题描述
在本题中,我们需要编写一个函数,该函数可以将任意正整数转换为相应的英文单词形式。此函数需要支持从0到999,999范围内的所有数字。
示例
numberToWords(0) === "zero"
numberToWords(1) === "one"
numberToWords(9) === "nine"
numberToWords(10) === "ten"
numberToWords(17) === "seventeen"
numberToWords(20) === "twenty"
numberToWords(21) === "twenty-one"
numberToWords(45) === "forty-five"
numberToWords(80) === "eighty"
numberToWords(99) === "ninety-nine"
numberToWords(100) === "one hundred"
numberToWords(301) === "three hundred one"
numberToWords(799) === "seven hundred ninety-nine"
numberToWords(800) === "eight hundred"
numberToWords(950) === "nine hundred fifty"
numberToWords(1000) === "one thousand"
numberToWords(1002) === "one thousand two"
numberToWords(3051) === "three thousand fifty-one"
numberToWords(7200) === "seven thousand two hundred"
numberToWords(7219) === "seven thousand two hundred nineteen"
numberToWords(8330) === "eight thousand three hundred thirty"
numberToWords(99999) === "ninety-nine thousand nine hundred ninety-nine"
numberToWords(888888) === "eight hundred eighty-eight thousand eight hundred eighty-eight"
解决方案
function numberToWords(n) {
function convertToWord(num) {
const singleDigits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
const tensPlace = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
if (num >= 0 && num <20) return singleDigits[num];
if (num >= 20 && num <100) return tensPlace[Math.floor(num / 10) - 2] + (num % 10 ? '-' + singleDigits[num % 10] : '');
if (num >= 100 && num <1000) return singleDigits[Math.floor(num / 100)] + ' hundred' + (num % 100 ? ' ' + convertToWord(num % 100) : '');
return convertToWord(Math.floor(num / 1000)) + ' thousand' + (num % 1000 ? ' ' + convertToWord(num % 1000) : '');
}
return convertToWord(n);
}
思路解析
为了实现这个功能,我首先定义了两个数组:一个是包含0到19的英文单词表示,另一个是包含20、30等十位数的英文单词表示。然后根据输入数字的不同范围(个位、十位、百位、千位),使用递归的方式进行转换。对于小于20的数字,直接返回对应单词;对于20到99的数字,通过计算十位和个位来构建单词;对于100到999的数字,先处理百位,再处理剩余部分;对于1000及以上的数字,先处理千位,再处理剩余部分。
遇到的挑战
主要难点在于处理不同位数的组合方式,尤其是当数字跨越多个位数时(如几百几千)。此外,确保每个部分之间正确的空格和连字符使用也是一个挑战。通过仔细分析每个数字范围并逐步调试,最终实现了完整的解决方案。