本文主要是介绍codewars,js实现5kyu:Write out numbers(数字转化为英文写法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 题目简介
- Example
- 我完成的代码
- 我的解题思路
- 我的难点
题目简介
该kata的链接地址
Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999.
Example
umber2words(0) ==> "zero"
number2words(1) ==> "one"
number2words(9) ==> "nine"
number2words(10) ==> "ten"
number2words(17) ==> "seventeen"
number2words(20) ==> "twenty"
number2words(21) ==> "twenty-one"
number2words(45) ==> "forty-five"
number2words(80) ==> "eighty"
number2words(99) ==> "ninety-nine"
number2words(100) ==> "one hundred"
number2words(301) ==> "three hundred one"
number2words(799) ==> "seven hundred ninety-nine"
number2words(800) ==> "eight hundred"
number2words(950) ==> "nine hundred fifty"
number2words(1000) ==> "one thousand"
number2words(1002) ==> "one thousand two"
number2words(3051) ==> "three thousand fifty-one"
number2words(7200) ==> "seven thousand two hundred"
number2words(7219) ==> "seven thousand two hundred nineteen"
number2words(8330) ==> "eight thousand three hundred thirty"
number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine"
number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight"
我完成的代码
function number2words(n){// works for numbers between 0 and 999999 function toWord(n){//定义好特别的数字var a = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"],b = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]//当n小于20时,可以直接获取if (n >= 0 && n < 20) return a[n];//当n大于等于20小于100时由...tyif (n >= 20 && n < 100) return b[Math.floor(n / 10) - 2] + (n % 10 ? '-' + a[n % 10] : '');//当n大于等于100小于1000时由...tyif (n >= 100 && n < 1000) return a[Math.floor(n / 100)] + ' hundred' + (n % 100 ? ' ' + toWord(n % 100) : '');//当n大于等于1000时return toWord(Math.floor(n / 1000)) + ' thousand' + (n % 1000 ? ' ' + toWord(n % 1000) : '');} return toWord(n)
}
我的解题思路
我的难点
这篇关于codewars,js实现5kyu:Write out numbers(数字转化为英文写法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!