题解 | #学英语#stack

学英语

https://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc

import java.math.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.stream.*;
import java.util.regex.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int num = in.nextInt();
        String[] levels = new String[] {"", "thousand", "million", "billion"};

        LinkedList<String> stack = new LinkedList<>();
        int levelsIndex = 0;
        while (num % 1000 != 0) {
            if (levelsIndex > 0) {
                stack.push(levels[levelsIndex]);
            }
            stack.push(getEnglish(num % 1000));
            levelsIndex++;
            num = num / 1000;
        }
        // 技巧
        System.out.println(String.join(" ", stack));
    }

    static String getEnglish(int num) {
        List<String> list = new ArrayList<>();
        String[] hundred = new String[] {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        String[] ten = new String[] {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
        String[] tenTwenty = new String[] {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};

        if (num / 100 > 0) {
            list.add(String.format("%s hundred", hundred[num / 100]));
        }

        num = num % 100;
        if (num >= 10 && num < 20) {
            list.add(tenTwenty[num - 10]);
        } else if (num >= 20) {
            if (num % 10 == 0) {
                list.add(String.format("%s", ten[num / 10]));
            } else {
                list.add(String.format("%s %s", ten[num / 10], hundred[num % 10]));
            }
        } else if (num < 10 && num > 0) {
            list.add(hundred[num % 10]);
        }
        return String.join(" and ", list);
    }
}


全部评论

相关推荐

挣K存W养DOG:我记得好多人说这个公司就是白嫖方案的,现在有大体方案要让你给他展示实现细节了,也是无敌了
点赞 评论 收藏
分享
用户64975461947315:这不很正常吗,2个月开实习证明,这个薪资也还算合理,深圳Java好多150不包吃不包住呢,而且也提前和你说了没有转正机会,现在贼多牛马公司骗你说毕业转正,你辛辛苦苦干了半年拿到毕业证,后面和你说没hc了😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务