您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Integer to English Words

2015-09-01 14:50 736 查看

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"

Hint:

Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.

Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.

There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

https://leetcode.com/problems/integer-to-english-words/

这题有毒,边界情况很多。

解法是递归处理千位以内的数,最后在后面加上"Thousand", "Million", "Billion"。

处理三位数的时候,先处理百位,剩下两位的数。

两位数又是两种,20以内的直接打表,21到99还要拆成个位和十位。

需要注意:

1. 零

2. 数字之间的空格

3. 1000000 --> One Million, 100000 --> One Hundred Thousand

/**
* @param {number} num
* @return {string}
*/
var numberToWords = function(num) {
var dict = {};
dict[0]= "Zero"; dict[1]= "One"; dict[2]= "Two"; dict[3]= "Three"; dict[4]= "Four"; dict[5]= "Five"; dict[6]= "Six";
dict[7]= "Seven"; dict[8]= "Eight"; dict[9]= "Nine"; dict[10]= "Ten"; dict[11]= "Eleven"; dict[12]= "Twelve";
dict[13]= "Thirteen"; dict[14]= "Fourteen"; dict[15]= "Fifteen"; dict[16]= "Sixteen"; dict[17]= "Seventeen";
dict[18]= "Eighteen"; dict[19]= "Nineteen"; dict[20]= "Twenty"; dict[30]= "Thirty"; dict[40]= "Forty"; dict[50]= "Fifty";
dict[60]= "Sixty"; dict[70]= "Seventy"; dict[80]= "Eighty"; dict[90]= "Ninety"; dict[100]= "Hundred";
var dict2 = ["Thousand", "Million", "Billion"];

if(num === 0){
return dict[0];
}
var res = "", c = -1;
while(num !== 0){
lessThanThousand(num % 1000);
num = parseInt(num / 1000);
c++;
}
return res.trim();

function lessThanThousand(n){
var str = "", count = 0;
//100 - 999
if(n >= 100){
count = parseInt(n / 100);
n = n % 100;
str += dict[count] + " " + dict[100];
}
//1 - 99
if(n !== 0){
if(str !== ""){
str += " ";
}
if(n <= 20){  //1 - 20
str += dict
;
}else{ //21 -99
var unitDigit = n % 10;
n = n - unitDigit;
str += unitDigit === 0 ? dict
: dict
+ " " + dict[unitDigit];
}
}
//"Thousand", "Million", "Billion"
if(c >= 0 && str !== ""){
str += " " + dict2[c] + " ";
}
res = (str + res).trim();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: