企业如何通过vue小程序开发满足高效运营与合规性需求
717
2022-09-04
273. 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"
思路: 这题的特点就是英语是以1000为单位进行操作的,不像汉语用“万”。 英语的另一个特点就是小于20的数字要特殊对待,整十的数字也要特殊对待。 一个数字num, 分为num<20, num<100提取整十,num<1000提取hundreds,再处理剩下小于100的部分。 大于1000的数字,有thuansands, million, billion. 1000以内的按上一行的方法处理。
class Solution { private static final String[] lessThan20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; private static final String[] tens = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; private static final String[] thousands = {"","Thousand","Million","Billion"}; public String numberToWords(int num) { if(num == 0) return "Zero"; String word = ""; int i = 0; while(num > 0){ if(num%1000 != 0){ word = helper(num%1000) + thousands[i] + " " + word; } num = num/1000; i++; } return word.trim(); } public String helper(int n) { if(n == 0){ return ""; } else if(n<20){ return lessThan20[n] + " "; } else if(n<100){ return tens[n/10] + " " + helper(n%10); } else { return lessThan20[n/100] + " Hundred " + helper(n%100); } }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~