您的位置:首页 > 其它

Leetcode: Integer to English Words

2015-12-26 00:08 417 查看
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"


Career Cup 150 Pg 442

Think of Convert(19,323,984) = Process(19) + "million" + Process(323) + "thousand" + Process(984) + ""

The Process is a process that generates words representation for integer below 1000

public class Solution {
String[] digits = new String[]{"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
String[] teen = new String[]{"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
String[] tens = new String[]{"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
String[] bigs = new String[]{"", "Thousand", "Million", "Billion"};

public String numberToWords(int num) {
String res = new String();
if (num == 0) return "Zero";
int count = 0;
while (num > 0) {
int belowThousand = num % 1000;
if (belowThousand != 0) {
res = process(belowThousand) + " " + bigs[count] + " " + res;
}
count++;
num = num / 1000;
}
return res.trim();
}

public String process(int n) {
String res = new String();
if (n/100 > 0) {
res = digits[n/100-1] + " " + "Hundred" + " ";
n = n%100;
}
if (n>=11 && n<=19) {
res = res + teen[n%10-1];
return res;
}
else if (n/10 > 0) {
res = res + tens[n/10-1] + " ";
n = n%10;
}
if (n > 0) {
res = res + digits[n-1];
}
return res.trim();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: