題目描述
Jessi初學英語,爲了快速讀出一串數字,編寫程序將數字轉換成英文:
如22:twenty two,123:one hundred and twenty three。
說明
數字爲正整數,長度不超過十位,不考慮小數,轉化結果爲英文小寫;
輸出格式爲twenty two;
非法數據請返回「error」;
關鍵字提示:and,billion,million,thousand,hundred。
方法原型:public static String parse(long num)
輸入描述:
輸入一個long型整數
輸出描述:
輸出相應的英文寫法
輸入例子:
2356
輸出例子:
two thousand three hundred and fifty six
算法實現
import java.util.Scanner;
/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
private final static String WORDS[] = {
"", "one", "two", "three", "four", "five",// 1-5
"six", "seven", "eight", "nine", "ten",// 6-10
"eleven", "twelve", "thirteen", "fourteen", "fifteen",// 11-15
"sixteen", "seventeen", "eighteen", "nineteen", "twenty",// 16-20
"thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"// 30-90
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNextLong()) {
long num = scanner.nextLong();
System.out.println(parse(num));
}
scanner.close();
}
private static String parse(long num) {
if (num <= 0) {
return "error";
} else if (num < 20) { // 20如下
return WORDS[(int) num];
} else if (num < 100) {
if (num % 10 == 0) {
return WORDS[(int) (20 + (num - 20) / 10)]; // 20 30 40 50 60 70 80 90
} else {
return parse(num / 10 * 10) + " " + parse(num % 10);
}
} else if (num < 1_000) { // 千如下
if (num % 100 == 0) {
return parse(num / 100) + " hundred";
} else {
return parse(num / 100) + " hundred and " + parse(num % 100);
}
} else if (num < 1_000_000) { // 百萬如下
if (num % 1_000 == 0) {
return parse(num / 1_000) + " thousand";
} else {
return parse(num / 1_000) + " thousand " + parse(num % 1_000);
}
} else if (num < 1_000_000_000) { // 億
if (num % 1_000_000 == 0) {
return parse(num / 1_000_000) + " million";
} else {
return parse(num / 1_000_000) + " million " + parse(num % 1_000_000);
}
} else if (num < 10_000_000_000L) { // 十億
if (num % 1_000_000_000 == 0) {
return parse(num / 1_000_000_000) + " billion";
} else {
return parse(num / 1_000_000_000) + " billion " + parse(num % 1_000_000_000);
}
} else {
return "error";
}
}
}