数字转成字母

发现一个有小坑的题目 Integer to English Words
题目要求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:
Input: 123
Output: "One Hundred Twenty Three"

Example 2:
Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:
Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

就是把一串数字按照英语语法格式输出成字符串的形式。英语不同于汉语,是3个一断。

汉语和英语数字表达的方式不同。汉语是个,十,百,千,万,十万,百万,千万,亿,十亿……,也就是以“十”的倍数来表示;而英语则是在数字超过千以后,以“千”(thousand)的倍数来表达的。如“一万”是“十千”,即 ten thousand;“十万”是“百千”,即 hundred thousand,直至“百万”,million。百万以上的数字则用“百万”的倍数表达;如“千万”是“十百万”,即 ten million;“亿”是“百百万”,即 hundred million,直至“十亿”,billion。 所以英文表达数字时可以从右往左,三位一逗号,逗号从右往左分别对应的是:thousand, million, billion, etc。


所以程序并不难想,思路也没有那么难,写完之后,一提交发现坑了,丫的最后面不能有空格,改了半天,最后实现了功能,发现代码很长,最后用了自带的函数trim,来去掉了多余的空格,代码也就将就算是自己能看过眼吧。
下面是丑代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @param {number} num
* @return {string}
*/
var numberToWords = function(num) {
//debugger
if(num === 0) return 'Zero'
let cous = ""
let index = 0
let a = [""," One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight"," Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen"]
let b = ["",""," Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety"]
let c = [""," Thousand", " Million", " Billion"]
let thereword = function (numb) {
if (numb === 0) return ""
let num_temp = ""
// debugger
if(numb > 99){
if(numb % 100 > 19) {
num_temp = a[parseInt(numb / 100)] + " Hundred" + b[parseInt((numb % 100) / 10)] + a[parseInt((numb % 100) % 10)]
} else {
num_temp = a[parseInt(numb / 100)] + " Hundred" + a[numb % 100]
}
} else {
if(numb > 19) {
num_temp = b[parseInt(numb / 10)] + a[numb % 10]
} else {
num_temp = a[numb]
}
}
return num_temp
}
while(num > 0) {
let nums = thereword(num % 1000)
if(nums !== "") {
cous = nums + c[index] + cous
} else {
cous = nums + cous
}
num = (num - num % 1000) / 1000
index++
}
return cous.trim()
};


以后需要注意更多的细节要求

感觉不错的话给博主赞助一下呗