[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(); } };
相关文章推荐
- JSP Tutorial
- JSP - Include Directive
- js 计算两个日期之间的月数
- js实现点击向下展开的下拉菜单效果代码
- Jsp里中文乱码的解决办法
- javascript的正则表达式
- freemarker从JSON中取值
- 关于使用tpl模板如何从模板中取数据放入js中
- js数据类型
- javascript实现父子页面数据传递
- js 计算两个日期之间的周数
- js标点符号全局匹配
- js核心--------作用域链了解
- js 数组容易弄混的那些方法
- JS实现自动倒计时
- js获取url参数
- Javascript:谈谈JS的全局变量跟局部变量
- 获取服务器端JSON数据
- 寄生组合式继承——《Javascript 高级程序设计》6.3.6
- JSP Custom tags with example – JSP Tutorial