LintCode刷题8
程序员文章站
2022-07-15 19:56:05
...
描述
把一个非负整数转成英文单词的形式。给定的输入一定比2^31-1
小。
样例
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
解题思路,将某个数字分为四个部分,分别为十亿、百万、千、个区分即可,需要注意符号之间的空格
public class Exp1305 {
/**
* @param num: a non-negative integer
* @return: english words representation
*/
public static String numberToWords(int num) {
String param =if(num==0){
return "Zero";
} "";
//1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
String Param1[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
//30,40,50,60,70,80,90
String Param2[] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
if (num > 999999999) {
param += Param1[(num / 1000000000)];
if (num % 1000000000 == 0) {
//如果出现几十亿后面没有任何数字的时候则没有空格
param += " billion";
return param;
}
//否则加入空格
param += " Billion ";
}
num %= 1000000000;
int n0_9991 = num / 1000000;
//999 000 000 - 001 000 000
if (n0_9991 > 0 && n0_9991 < 1000) {
if (n0_9991 / 100 > 0) {
//0-999是需要不加后缀 所以需要区分
param += Param1[(n0_9991 / 100)];
param += " Hundred";
if (n0_9991 % 100 != 0) {
param += " ";
}
}
n0_9991 %= 100;
if (n0_9991 < 20) {
//1-19
param += Param1[n0_9991];
} else {
//20-99
param += Param2[(n0_9991 / 10) - 2];
if (n0_9991 % 10 != 0) {
param += " ";
param += Param1[n0_9991 % 10];
}
}
param += " Million";
if(num % 1000000!=0){
param += " ";
}
}
num %= 1000000;
int n0_9992 = num / 1000;
//999 000 - 001 000
if (n0_9992 > 0 && n0_9992 < 1000) {
if (n0_9992 / 100 > 0) {
//0-999是需要不加后缀 所以需要区分
param += Param1[(n0_9992 / 100)];
param += " Hundred";
if (n0_9992 % 100 != 0) {
param += " ";
}
}
n0_9992 %= 100;
if (n0_9992 < 20) {
//1-19
param += Param1[n0_9992];
} else {
//20-99
param += Param2[(n0_9992 / 10) - 2];
if (n0_9992 % 10 != 0) {
param += " ";
param += Param1[n0_9992 % 10];
}
}
param += " Thousand";
if(num % 1000!=0){
param += " ";
}
}
int n0_999 = num %= 1000;
//0-999
if (n0_999 > 0 && n0_999 < 1000) {
if (n0_999 / 100 > 0) {
//0-999是需要不加后缀 所以需要区分
param += Param1[(n0_999 / 100)];
param += " Hundred";
if (n0_999 % 100 == 0) {
//300就不需要后面加空格,然后return 即可
param += "";
return param;
} else {
param += " ";
}
}
n0_999 %= 100;
if (n0_999 < 20) {
//1-19
param += Param1[n0_999];
} else {
//20-99
param += Param2[(n0_999 / 10) - 2];
if (n0_999 % 10 != 0) {
param += " ";
param += Param1[n0_999 % 10];
}
}
}
return param;
}
public static void main(String[] args) {
//for(int i = 1;i<1000;i++)
System.out.println(numberToWords(123));
}
}