码迷,mamicode.com
首页 > 其他好文 > 详细

273. Integer to English Words

时间:2018-08-27 14:03:28      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:rtt   rip   要求   div   数字   use   符号   tco   out   

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

要求把一个数字转换成英语。

1,000,000,000,000

想到没三位可以成一组,每组内的形成方式是一样的。只是最后加的千位符号不一样 -- "","Thousand", "Million", "Billion", "Trillion"

所以我们可以把三位为一组。先实现三位数的表示方法。再递归调用这个方法。

 

这个题的时间复杂度基本是O(N) recursion 的深度也不回太深。

对于Integer 最大值: 2^31-1 = 2,147,483,647  about 2 billion

一个估算方法 

2^10 is very near to 1000,

so 2^(3*10) is 1000^3 or about 1 billion.

One of the 32 bits is used for sign, so the max value is really only 2^31

which is about twice the amount you get for 2^(3*10): = 2 billion

 

 String[] belowTwenty = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",     "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
 String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
 String[] beyond = new String[]{"","Thousand", "Million","Billion", "Trillion"};
  
    public String numberToWords(int num) {
      if(num == 0){
        return "Zero";
      }
      return helper(num, 0).trim(); //主程序中递归调用三位数
    }

private String helper(int num, int count){ if(num == 0) return ""; String higher = helper(num/1000, count +1); String ans = convertToNNN(num%1000); if(ans.length() > 0) { return higher + " " + ans + " " + beyond[count] ; } return higher; } //形成三位数 private String convertToNNN(int num){ if(num < 100){ return convertToNN(num); } if(num % 100 == 0){ return belowTwenty[num/100] + " Hundred"; } return belowTwenty[num/100] + " Hundred " + convertToNN(num % 100); }
//形成两位数
private String convertToNN(int num){ if(num < 20){ return belowTwenty[num]; } if(num % 10 == 0){ return belowHundred[num/10]; } return belowHundred[num/10] + " " + belowTwenty[num%10]; }

 

273. Integer to English Words

标签:rtt   rip   要求   div   数字   use   符号   tco   out   

原文地址:https://www.cnblogs.com/HUTONG749/p/9541556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!