LeetCode 273. Integer to English Words
原题链接在这里:https://leetcode.com/problems/integer-to-english-words/
题目:
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"
题解:
没三个digit分成一个 unit, 用unitNumber 函数把这三位数换算成数字加上对应的unit.
Note: num = 1,000,000时不可以出现 "One Million Thousand"的情况,所以while循环时 要加上if(rest>0)的限定条件.
Time Complexity: O(n), n是unit的个数 Space: O(1).
AC Java:
1 public class Solution { 2 public String numberToWords(int num) { 3 if(num == 0){ 4 return "Zero"; 5 } 6 String res = ""; 7 String [] units = {"", " Thousand", " Million", " Billion"}; 8 int i = 0; 9 while(num > 0){ 10 int unit = num%1000; 11 if(unit > 0){ //error 1,000,000 12 res = unitNumber(unit) + units[i] + (res.length() == 0 ? "" : " "+res); 13 } 14 num = num/1000; 15 i++; 16 } 17 return res; 18 } 19 20 private String unitNumber(int unit){ 21 String res = ""; 22 String [] ten = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; 23 String [] twenty ={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; 24 String [] hundred = {"Zero","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; 25 26 int a = unit/100; 27 int b = unit%100; 28 int c = unit%10; 29 30 if(a > 0){ 31 res = ten[a] + " Hundred"; 32 } 33 34 if(b>=10 && b<20){ 35 if(res.length() != 0){ 36 res = res + " "; 37 } 38 res = res + twenty[b%10]; 39 return res; 40 }else if(b >= 20){ 41 if(res.length() != 0){ 42 res = res + " "; 43 } 44 b = b/10; 45 res = res + hundred[b]; 46 } 47 48 if(c > 0){ 49 if(res.length() != 0){ 50 res = res + " "; 51 } 52 res = res + ten[c]; 53 } 54 return res; 55 } 56 }