题目描述:
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
如22:twenty two,123:one hundred and twenty three。
说明:
数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
输出格式为twenty two;
非法数据请返回“error“;
输入描述:
输入一个long型整数
输出描述:
输出相应的英文写法
思路:
每3位处理一次,并对3位进行翻译
import java.util.Scanner;
public class Main
{
public static String[] arr1 = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
public static String[] arr2 = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
public static String[] arr3 = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
long num = scanner.nextLong();
System.out.println(convert(num));
}
}
public static String convert(Long num)
{
String res = "";
if (num < 0) return "error";
long billion = num / 1000000000;
num = num % 1000000000;
long million = num / 1000000;
num = num % 1000000;
long thousand = num / 1000;
num = num % 1000;
if (billion != 0)
res += converHelp(billion) + " billion";
if (million != 0 && !res.equals(""))
res += " " + converHelp(million) + " million";
else if (million != 0 && res.equals(""))
res += converHelp(million) + " million";
if (thousand != 0 && !res.equals(""))
res += " " + converHelp(thousand) + " thousand";
else if (thousand != 0 && res.equals(""))
res += converHelp(thousand) + " thousand";
if (num != 0 && !res.equals(""))
res += " " + converHelp(num);
else if (num != 0 && res.equals(""))
res += converHelp(num);
return res;
}
public static String converHelp(long num)
{
String res = "";
long hundred = num / 100;
long ten = (num % 100) / 10;
long unit = num % 10;
if (ten == 0 && unit != 0)
res += arr1[(int)unit];
else if (ten != 0 && unit == 0)
res += arr3[(int)(ten - 1)];
else if (ten != 0 && unit != 0)
{
if (ten == 1)
res += arr2[(int)(unit - 1)];
else
res += arr3[(int)(ten - 1)] + " " + arr1[(int)unit];
}
if (hundred != 0)
res = arr1[(int)hundred] + " hundred and " + res;
return res;
}
}