递归

学英语

http://www.nowcoder.com/questionTerminal/1364723563ab43c99f3d38b5abef83bc

对于本题,需要找出重复性,按照英文数字的范围,每三位隔一次,如000,000,000,由于范围已经限定在9位以内,同时,每三位就相当于一个范围,即百万、千,那么,最后的递归只要找到三位以内的判断

import java.util.*;

public class Main{

    public static String[] ones = new String[]{"zero","one","two","three","four","five","six","seven","eight","nine"};
    public static String[] tens = new String[]{"ten","eleven","twelve","thirteen","forteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
    public static String[] twieties = new String[]{"zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};

    public static int[] range = new int[]{(int)1e2, (int)1e3, (int)1e6, (int)1e9, (int)1e12};
    public static String[] ranges = new String[]{"hundred", "thousand", "million", "billion"};

    public static void main(String[] args){
        // 管道流
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            // 获取数值
            int num = sc.nextInt();
            // 转换
            System.out.println(transfer(num));
        }
    }

    public static String transfer(int num){
        // terminor
        if(num <= 9) return ones[num];
        if(num <= 19) return tens[num % 10];
        if(num <= 99) return twieties[num / 10] + (num % 10 == 0 ? "" : " " + ones[num % 10]);

        // 递归调用
        for(int i=0; i<4; i++){
            if(num < range[i + 1]){
                return transfer(num / range[i]) + " " + ranges[i] + 
                    (num % range[i] == 0 ? " " : (i != 0 ? " " : " and ") + transfer(num % range[i]));
            }
        }
        return "";
    }
}
全部评论

相关推荐

迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
评论
28
11
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务