题目描述
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型整数
输出描述:
输出相应的英文写法
示例1
输入
2356
输出
two thousand three hundred and fifty six
思路:1、由不超过九位数和英语中的读法,可以看出每三位处理一次;
2、在11-19之间的读法和20-99读法不同,编程实现的话,需要把这些定义为静态数组来调用,同时在判断的时候分
情况来讨论,注意对if和else的分类;
3、使用/来进行位的判断,使用%来截取后面的数字的部分;
4、结构上有分主函数、题目要求的函数、转换数字为字符串的函数;
代码实现:
import java.util.*; public class Main{ public static String[] bit_num = {"zero","one","two","three","four","five","six","seven","eight","nine"}; public static String[] ten_num = {"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}; public static String[] twenty_more = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}; public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(sc.hasNext()){ Long n=sc.nextLong(); String str=parse(n); System.out.println(str); } sc.close(); } public static String parse(long num){ if(num < 0) return "error"; StringBuffer sb=new StringBuffer(); long billion = num / 1000000000; if(billion != 0){ sb.append(trans(billion) + " billion "); } num %= 1000000000; long million = num / 1000000; if(million != 0){ sb.append(trans(million) + " million "); } num %= 1000000; long thousand = num / 1000; if(thousand != 0){ sb.append(trans(thousand) + " thousand "); } num %= 1000; long hundred = num; if(hundred != 0){ sb.append(trans(hundred)); } return sb.toString().trim();//去掉首尾的空格 } public static String trans(long num){ StringBuffer sb = new StringBuffer(); int h = (int)(num / 100); if(h != 0){ sb.append(bit_num[h] + " hundred"); } num %= 100; int t = (int)(num / 10); if(t != 0){ if(h != 0){ sb.append(" and "); } if(t == 1){ sb.append(ten_num[(int)(num%10)]); } else{ sb.append(twenty_more[(int)(t - 2)] + " "); if(num % 10 != 0){ sb.append(bit_num[(int)(num%10)]); } } } else if(num % 10 != 0){ if(h != 0){ sb.append(" and "); } sb.append(bit_num[(int)(num%10)]); } return sb.toString().trim(); } }