题解 | #学英语#

学英语

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

import java.util.*;


public class Main {
    public static void main(String[] args) {
        // 数字到英语的基本映射
        String[] ones = {
                "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
                "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
        };

        String[] tens = {
                "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
        };

        String[] units = {
                "", "thousand", "million", "billion"
        };

        Scanner fzhinput = new Scanner(System.in);
        long sz = fzhinput.nextLong(); // 从输入读取一个long型数字

        if (sz == 0) {
            System.out.println("zero");
            return;
        }

        // 使用 StringBuilder 存储转换结果
        StringBuilder result = new StringBuilder();
        int unitIndex = 0;

        // 将数字转换为英文的逻辑
        while (sz > 0) {
            int part = (int) (sz % 1000);

            if (part > 0) {
                StringBuilder partResult = new StringBuilder();
                int hundred = part / 100;
                int remainder = part % 100;

                if (hundred > 0) {
                    partResult.append(ones[hundred]).append(" hundred");
                    if (remainder > 0 && part < 1000) {
                        partResult.append(" and ");
                    }
                }

                if (remainder < 20) {
                    partResult.append(ones[remainder]);
                } else {
                    partResult.append(tens[remainder / 10]);
                    if (remainder % 10 > 0) {
                        partResult.append(" ").append(ones[remainder % 10]);
                    }
                }

                if (result.length() > 0) {
                    result.insert(0, " ");
                }

                result.insert(0, partResult.toString() + (units[unitIndex].isEmpty() ? "" : " " + units[unitIndex]));
            }

            sz /= 1000;
            unitIndex++;
        }

        // 输出结果
        System.out.println(result.toString().trim());
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务