首页 > 试题广场 >

学英语

[编程题]学英语
  • 热度指数:113669 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:

具体规则如下:
1.在英语读法中三位数字看成一整体,后面再加一个计数单位。从最右边往左数,三位一单位,例如12,345 等
2.每三位数后记得带上计数单位 分别是thousand, million, billion.
3.公式:百万以下千以上的数 X thousand X, 10亿以下百万以上的数:X million X thousand X, 10 亿以上的数:X billion X million X thousand X. 每个X分别代表三位数或两位数或一位数。
4.在英式英语中百位数和十位数之间要加and,美式英语中则会省略,我们这个题目采用加上and,百分位为零的话,这道题目我们省略and

下面再看几个数字例句:
22: twenty two
100:  one hundred
145:  one hundred and forty five
1,234:  one thousand two hundred and thirty four
8,088:  eight thousand (and) eighty eight (注:这个and可加可不加,这个题目我们选择不加)
486,669:  four hundred and eighty six thousand six hundred and sixty nine
1,652,510:  one million six hundred and fifty two thousand five hundred and ten

说明:
数字为正整数,不考虑小数,转化结果为英文小写;
保证输入的数据合法
关键字提示:and,billion,million,thousand,hundred。

数据范围:



输入描述:

输入一个long型整数



输出描述:

输出相应的英文写法

示例1

输入

22

输出

twenty two
这个题目的and的位置着实让人有点抓狂,题目的意思是只有百位之后才有and,如果百位上为0,就不加用and了。
2016按照题目的意思就是two thousand sixteen,但我觉得按照英语说法的习惯,two thousand and sixteen要更好一些。

下面是我的答案
如果把函数里面的注释去掉,就是我认为的“比较好”的答案。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

const vector<string> zeroToNine = {"zero", "one", "two", "three", "four",
                                   "five", "six", "seven", "eight", "nine"};

const vector<string> tenToNineteen = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
                                      "sixteen", "seventeen", "eighteen", "nineteen"};

const vector<string> tenToNinety = {"ten", "twenty", "thirty", "forty", "fifty",
                                    "sixty", "seventy", "eighty", "ninety"};

const vector<string> thousandToBillion = {"thousand", "million", "billion"};

// 处理小于1000的部分
// isBegin用来表示当前的3位数是否位于数字的最高位部分
// 如果是则某些两位数或一位数之前不用加and
void processThousand(int N, vector<string> &result, bool isBegin)
{
    vector<int> inners;
    while (N >= 10)
    {
        inners.push_back(N % 10);
        N /= 10;
    }
    inners.push_back(N);

    // 三位数
    if (inners.size() == 3)
    {
        result.push_back(zeroToNine[inners[2]]);
        result.push_back("hundred");

        if (inners[1] == 0)
        {
            if (inners[0] > 0)
            {
                result.push_back("and");
                result.push_back(zeroToNine[inners[0]]);
            }
        }
        else if (inners[1] == 1)
        {
            result.push_back("and");
            result.push_back(tenToNineteen[inners[0]]);
        }
        else
        {
            result.push_back("and");
            result.push_back(tenToNinety[inners[1] - 1]);
            if (inners[0] > 0)
            {
                result.push_back(zeroToNine[inners[0]]);
            }
        }
    }
    // 两位数
    else if (inners.size() == 2)
    {
        if (inners[1] == 1)
        {
            /*
            if (! isBegin)
            {
                result.push_back("and");
            }
             */
            result.push_back(tenToNineteen[inners[0]]);
        }
        else
        {
            /*
            if (! isBegin)
            {
                result.push_back("and");
            }*/
            result.push_back(tenToNinety[inners[1] - 1]);
            if (inners[0] > 0)
            {
                result.push_back(zeroToNine[inners[0]]);
            }
        }
    }
    // 一位数
    else
    {
        if (! isBegin)
        {
            if (inners[0] > 0)
            {
                // result.push_back("and");
                result.push_back(zeroToNine[inners[0]]);
            }
        }
        else
        {
            result.push_back(zeroToNine[inners[0]]);
        }
    }
}

int main()
{

    int N;

    while (cin >> N)
    {
        int thousandPart = 0;
        vector<int> thousands;

        vector<string> result;

        while (N >= 1000)
        {
            thousands.push_back(N % 1000);
            N /= 1000;
            ++thousandPart;
        }

        thousands.push_back(N);

        if (thousandPart == 0)
        {
            // 1000以下
            processThousand(N, result, true);
        }
        else
        {
            // 按1000分 最高位的部分
            processThousand(thousands[thousandPart], result, true);
            result.push_back(thousandToBillion[thousandPart - 1]);

            // 中间部分
            for (int i = thousandPart - 1; i >= 1; --i)
            {
                processThousand(thousands[i], result, false);
                if (thousands[i] > 0)
                {
                    result.push_back(thousandToBillion[i - 1]);
                }
            }

            // 最后小于1000的部分
            processThousand(thousands[0], result, false);
        }

        for (int i = 0; i < result.size() - 1; ++i)
        {
            cout << result[i] << " ";
        }
        cout << result[result.size() - 1] << endl;
    }

    return 0;
}

发表于 2016-08-15 15:59:43 回复(4)
这道题不算难,就是得梳理英文表示数字的语法规则后再总结归纳一下,然后联想到老外都喜欢用','分隔每三个数位,想明白这里基本上大逻辑就对了,但是细分逻辑其实蛮复杂,还得学英语😂,而且顾及到代码的可读性、合理性、模块化和书写的整洁性。总之就是磨人.......
下面给出我的解法,其实也可以当博客看了,思路理解起来应该还算清晰。
使用的内存空间也是超过了97%的解法。

import java.util.Scanner;

/**
 * @author Yuliang.Lee
 * @version 1.0
 * @date 2021/9/20 11:24
 * 学英语:
    Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文:
    如22:twenty two,123:one hundred and twenty three。
    说明:
    数字为正整数,长度不超过九位,不考虑小数,转化结果为英文小写;
    输出格式为twenty two;
    非法数据请返回“error”;
    关键字提示:and,billion,million,thousand,hundred。

 * 解题思路:
    a.先判断输入的数是否不超过9位,且不能有负号,不能含小数点,然后用0补足得到9位字符数组。
    b.根据英文的数字表示法,每3个数字分隔为一组来处理,从左往右看:
        1~3位数,计量单位为million
        4~6位数,计量单位为thousand
        7~9位数,计量单位为hundred and 十位-个位 (注意对10-19的英文单词额外处理)
    c.million和thousand单位中的个十百的计数法则同7~9位数。
    d.最后将整合后的结果进行输出。

 * 示例:
    输入:2356 (2,356)
    输出:two thousand three hundred and fifty six

    输入:123000123 (123,000,123)
    输出:one hundred and twenty three million one hundred and twenty three

    输入:1000000 (1,000,000)
    输出:one million
 */
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String figure = in.nextLine();
            if (isLegal(figure)) {
                char[] digits = String.format("%09d", Integer.parseInt(figure)).toCharArray();
                StringBuilder output = new StringBuilder();
                for (int i = 0; i < 9; i += 3) {
                    String tmpResult = transferHundredsDigit(digits, i, i + 3);
                    if (tmpResult != null && tmpResult.length() != 0) {
                        output.append(tmpResult);
                        switch (i) {
                            case 0:
                                output.append("million ");
                                break;
                            case 3:
                                output.append("thousand ");
                                break;
                            case 6:
                                output.append(" ");
                                break;
                            default:
                                break;
                        }
                    }
                }
                if (output.length() == 0) {
                    output.append("zero ");
                }
                System.out.println(output.substring(0, output.length() - 1));
            }
            else {
                System.out.println("error");
            }
        }
    }


    /**
     * 合法性校验
     * @param figure
     * @return
     */
    public static boolean isLegal(String figure) {
        if (figure.length() > 9
                || figure.contains("-")
                || figure.contains(".")) {
            return false;
        }
        return true;
    }


    /**
     * 个十百的转换
     * @param digits
     * @return
     */
    public static String transferHundredsDigit(char[] digits, int start, int end) {
        boolean hasAnd = false;
        boolean isTeen = false;
        StringBuilder result = new StringBuilder();
        for (int i = start; i < end; i++) {
            // 当十位为1时
            if (isTeen) {
                result.append(transferTeen(digits[end - 1]));
                break;
            }
            // 百位和个位
            if (i == start || i == end - 1) {
                switch (digits[i]) {
                    case '0':
                        break;
                    case '1':
                        result.append("one ");
                        break;
                    case '2':
                        result.append("two ");
                        break;
                    case '3':
                        result.append("three ");
                        break;
                    case '4':
                        result.append("four ");
                        break;
                    case '5':
                        result.append("five ");
                        break;
                    case '6':
                        result.append("six ");
                        break;
                    case '7':
                        result.append("seven ");
                        break;
                    case '8':
                        result.append("eight ");
                        break;
                    case '9':
                        result.append("nine ");
                        break;
                    default:
                        break;
                }
                if (i == start && digits[i] != '0') {
                    hasAnd = true;
                    result.append("hundred ");
                }
            }
            // 十位
            else {
                if (hasAnd && (digits[i] != '0' || digits[i + 1] != '0')) {
                    result.append("and ");
                }
                switch (digits[i]) {
                    case '0':
                        break;
                    case '1':
                        isTeen = true;
                        break;
                    case '2':
                        result.append("twenty ");
                        break;
                    case '3':
                        result.append("thirty ");
                        break;
                    case '4':
                        result.append("forty ");
                        break;
                    case '5':
                        result.append("fifty ");
                        break;
                    case '6':
                        result.append("sixty ");
                        break;
                    case '7':
                        result.append("seventy ");
                        break;
                    case '8':
                        result.append("eighty ");
                        break;
                    case '9':
                        result.append("ninety ");
                        break;
                    default:
                        break;
                }
            }
        }
        return result.toString();
    }


    /**
     * 10~19对应的英文单词转译
     * @param number
     * @return
     */
    public static String transferTeen(char number) {
        switch (number) {
            case '0':
                return "ten ";
            case '1':
                return "eleven ";
            case '2':
                return "twelve ";
            case '3':
                return "thirteen ";
            case '4':
                return "fourteen ";
            case '5':
                return "fifteen ";
            case '6':
                return "sixteen ";
            case '7':
                return "seventeen ";
            case '8':
                return "eighteen ";
            case '9':
                return "nineteen ";
            default:
                return "";
        }
    }
}


发表于 2021-09-20 17:47:03 回复(1)
我的程序很长,你忍一下。
import java.util.Scanner;

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","fourteen","fifteen","sixteen",
            "seventeen","eighteen","nineteen"};
    public static String[] twenty = new String[]{"zero","ten","twenty","thirty","forty",
            "fifty","sixty","seventy","eighty","ninety"};
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            long num = sc.nextLong();
            System.out.println(numToWord(num));
        }
    }
    private static String numToWord(long num){
        StringBuilder stringBuilder = new StringBuilder();
        if(num>=1000000000){
            String word = hundredWord((int)num/1000000000);
            num = num%1000000000;
            stringBuilder.append(" ").append(word).append(" billion");
        }
        if(num>=1000000){
            String word = hundredWord((int)num/1000000);
            num = num%1000000;
            stringBuilder.append(" ").append(word).append(" million");
        }
        if(num>=1000){
            String word = hundredWord((int)num/1000);
            num = num%1000;
            stringBuilder.append(" ").append(word).append(" thousand");
        }
        if(num!=0){
            String word = hundredWord((int)num);
            stringBuilder.append(" ").append(word);
        }
        return stringBuilder.toString().trim();
    }
    private static String hundredWord(int num){
        StringBuilder stringBuilder = new StringBuilder();
        if(num>=100){
            stringBuilder.append(ones[num/100]).append(" hundred");
            num = num%100;
        }
        if(stringBuilder.length() != 0)stringBuilder.append(" and ");
        if(num>=20){
            stringBuilder.append(twenty[num/10]);
            num = num%10;
            if(num!=0)stringBuilder.append(" ").append(ones[num]);
        }else if(num>=10){
            stringBuilder.append(tens[num%10]);
        }else{
            stringBuilder.append(ones[num]);
        }
        return stringBuilder.toString().trim();
    }
}


发表于 2021-08-05 20:25:35 回复(0)
//每3位处理一次,并对3位进行翻译
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 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();
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            long num = in.nextLong();
            System.out.println(parse(num));
        }
        in.close();
    }
}

发表于 2017-03-18 17:34:28 回复(1)
import java.util.*;

public class Main {
    static String[] to19 = new String[]{"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
    static String[] tens = new String[]{"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","hundred"};
    static String[] hundreds = {"", "thousand", "million", "billion"};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        Stack<String> stk = new Stack<>();
        StringBuilder stb = new StringBuilder();
        while (n > 0) {
            long m = n % 1000;
            if (m >= 100) {
                stb.append(to19[(int)m/100]).append(" ").append(tens[10]).append(" ");
            }
            if(m%100>0){
                if(stb.length()>0) stb.append("and ");
                if(m%100>=20){
                    stb.append(tens[(int) ((m%100)/10)]).append(" ");
                    if(m%10>0){
                        stb.append(to19[(int) (m%10)]).append(" ");;
                    }
                }else{
                    stb.append(to19[(int) (m%100)]).append(" ");;
                }
            }
            stb.append("");
            n/=1000;
            stk.push(stb.toString());
            stb.delete(0,stb.length());
        }
        while (stk.size()>0) {
            stb.append(stk.pop()).append(hundreds[stk.size()]).append(" ");
        }
        System.out.println(stb.substring(0,stb.length()-1));
    }


}

发表于 2022-07-06 22:53:46 回复(0)
#没用字典,用的列表,有些边界值额外处理了以下
def spk(number):  #每3位数分开处理
    list1 = ["","one","two","three","four","five","six","seven","eight","nine","ten"]
    list2 = ["","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
    list3 = ["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]
    if number < 11:     #处理 1-10
        r = list1[number]
    elif 10 < number < 20:    #处理 11-19
        r = list2[number%10]
    elif 19 < number < 100:   #处理 20-99
        r = list3[number//10] + " " + list1[number%10]
    elif number == 100:      # 单独处理 100,用字典就没这么麻烦
        r = "one hundred"
    else:      #处理 101-999,方法和上面一样
        h = list1[number//100] + " hundred and"   
        if number%100 < 11:
            t = list1[number%100]
        elif 10 < number%100 < 20:
            t = list2[number%100%10] 
        elif 19 < number%100 < 100:
            t = list3[number%100//10] + " " + list1[number%100%10]
        r = h + " " + t     #把结果组合起来
    return r    #返回结果

while True:
    try:
        strs = input()
        if len(strs) < 4:    #只有3位的情况
            number = int(strs)
            res = spk(number)
            print(res)
        elif 3 < len(strs) < 7:    # 有4-6位的情况
            number = int(strs)//1000
            r1 = spk(number)
            number = int(strs)%1000
            r2 = spk(number)
            res = r1 + " thousand " + r2   #因为前面函数是每3位一组,现在组合结果
            res = res.replace("  "," ")    #因为用的前面列表,会有双空格的情况,额外处理
            print(res)
        elif 6 < len(strs) < 8:     #7位数的情况
            number = int(strs)//1000000
            r1 = spk(number)
            number = int(strs)%1000000//1000
            r2 = spk(number)
            number = int(strs)%1000000%1000
            r3 = spk(number)
            res = r1 + " million " + r2 + " thousand " + r3   #因为前面函数是每3位一组,现在组合结果         
            res = res.replace("  "," ")    #因为用的前面列表,会有双空格的情况,额外处理
            print(res)                
    except:
        break
#还是觉得很复杂,倒是挺好理解
发表于 2022-05-26 17:44:47 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        // 预设字典
        String[] dic1 = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        String[] dic2 = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
        String[] dic3 = {"zero","ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
        String[] dic4 = {"", "thousand", "million", "billion"};
        while(in.hasNextLine()){
            // 输入的处理
            String num = in.nextLine();
            StringBuilder res = new StringBuilder();
            String zero = "";
            if((num.length() % 3) != 0){
                for(int i = 0; i < (3 - num.length() % 3); i++){
                    zero += "0";
                }
            }
            num = zero + num;
            // 每三个一位进行处理,最多处理到billion
            int n = num.length();
            int i = 0;
            List<String> list = new ArrayList<>();
            while(n >= 3){
                StringBuilder builder = new StringBuilder();
                String str = num.substring(n - 3, n);
                int a = str.charAt(0) - '0';
                int b = str.charAt(1) - '0';
                int c = str.charAt(2) - '0';
                boolean aIsZero = false;
                boolean bIsZero = false;
                boolean cIsZero = false;
                // 百位
                if(a != 0){
                    builder.append(dic1[a] + " hundred");
                }else{
                    aIsZero = true;
                }
                if(!aIsZero && (b != 0 || c != 0)){
                    builder.append(" and");
                }
                String kongge = aIsZero ? "" : " ";
                // 十位
                if(b != 0){
                    if(b == 1){
                        int temp = b * 10 + c - 10;
                        builder.append(kongge + dic2[temp]);
                    }else{
                        builder.append(kongge + dic3[b] + (c == 0 ? "" : (" " + dic1[c])));
                    }
                }else{
                    bIsZero = true;
                }
                // 个位
                if(c != 0){
                    if(bIsZero){
                        builder.append(kongge + dic1[c]);
                    }
                }else{
                    cIsZero = true;
                }
                // 最后的单位
                if(!aIsZero || !bIsZero || !cIsZero){
                    builder.append((i == 0 ? "" : " ") + dic4[i]);
                    list.add(builder.toString());
                }
                // 更新索引
                n -= 3;
                i++;
            }
            // 输出的处理
            for(int j = list.size() - 1; j >= 0; j--){
                if(j != 0){
                    res.append(list.get(j) + " ");
                }else{
                    res.append(list.get(j));
                }
            }
            System.out.println(res);
        }
    }
}

发表于 2022-04-09 20:03:10 回复(0)
import java.util.Scanner;

public class Main {
    public static String[] ones = new String[]{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    public static String[] teens = new String[]{"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    public static String[] tys = new String[]{"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    public static String[] hundreds = new String[] {"hundred", "thousand", "million", "billion"};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            System.out.println(numToEn(sc.next()));
        }
    }

    // 数字转英文
    public static String numToEn(String num) {
        String temp;
        // 个位
        if (num.length() == 1) {
            return ones[num.charAt(0)-48];
        }
        // 十位
        if (num.length() == 2) {
            if (num.startsWith("0")) {
                return ones[num.charAt(1)-48];
            }
            if (num.startsWith("1")) {
                return teens[num.charAt(1)-48];
            } else {
                temp = tys[num.charAt(0)-48];
                if (num.endsWith("0")) {
                    return temp;
                } else {
                    return temp + " " + ones[num.charAt(1)-48];
                }
            }
        }
        // 百位(递归) 注意:hundred后用and来连接
        if (num.length() == 3) {
            if (num.startsWith("0")) {
                return numToEn(num.substring(1));
            }
            temp = numToEn(num.substring(0, 1)) + " " +  hundreds[0];
            if (num.endsWith("00")) {
                return temp;
            } else {
                return temp + " and " + numToEn(num.substring(1));
            }
        }
        // 千位(递归)
        if (num.length() < 7) {
            if (num.startsWith("0")) {
                return numToEn(num.substring(1));
            }
            temp = numToEn(num.substring(0, num.length()-3)) + " " + hundreds[1];
            if (num.endsWith("000")) {
                return temp;
            } else {
                return temp + " " + numToEn(num.substring(num.length()-3));
            }
        }
        // 百万位(递归)
        if (num.length() < 10) {
            if (num.startsWith("0")) {
                return numToEn(num.substring(1));
            }
            temp = numToEn(num.substring(0, num.length()-6)) + " " + hundreds[2];
            if (num.endsWith("000000")) {
                return temp;
            } else {
                return temp + " " + numToEn(num.substring(num.length()-6));
            }
        }
        // 十亿位(递归)
        temp = numToEn(num.substring(0, num.length()-10)) + " " + hundreds[3];
        if (num.endsWith("000000000")) {
            return temp;
        } else {
            return temp + " " + numToEn(num.substring(num.length()-10));
        }
    }
}

发表于 2021-11-07 22:22:23 回复(0)
//3位一处理,这道题好tm烦人,写了几个小时!!!
import java.util.Scanner;

public class Main{
    private static String[] ge = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    private static String[] shi = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    private static String[] teen = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen","nineteen"};
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            long num = sc.nextLong();
            String s = toEnglish(num);
            System.out.println(s);
        }
    }
    
    //转为英语,3位一起处理
    private static String toEnglish(long num){
        String str = String.valueOf(num);
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        int m=len/3, n=len%3;
        int sep = 0;
        for(; sep<m; sep++){
            String s = str.substring(len-3-3*sep,len-3*sep);
            sb.insert(0,english1(s, sep));
        }
        if(n!=0) sb.insert(0, english2(str.substring(0, n), sep));
        return sb.toString();
    }
    
    //处理三位数
    private static String english1(String s, int i){
        StringBuilder sb = new StringBuilder();
        char c1 = s.charAt(0);
        char c2 = s.charAt(1);
        char c3 = s.charAt(2);
        if(c1=='0' && c2=='0' && c3=='0') return "";
        if(c1!='0') sb.append(ge[c1-'0'-1]).append(" hundred");
        if(c2!='0' || c3!='0'){
            if(c1!='0') sb.append(" and ");
            if(c2=='1') sb.append(teen[c3-'0']);
            else if(c2=='0') sb.append(ge[c3-'0'-1]);
            else{
                sb.append(shi[c2-'0'-2]);
                if(c3!='0'){
                    sb.append(" ").append(ge[c3-'0'-1]);
                }
            }
        }
        switch(i){
            case 0: break;
            case 1: sb.append(" ").append("thousand ");break;
            case 2: sb.append(" ").append("million ");break;
            case 3: sb.append(" ").append("billion ");break;
            default: ;
        }
        return sb.toString();
    }
    
    //处理剩余数字
    private static String english2(String s, int i){
        StringBuilder sb = new StringBuilder();
        int len = s.length();
        if(len==1) sb.append(ge[s.charAt(0)-'0'-1]);
        else{
            int c1 = s.charAt(0);
            int c2 = s.charAt(1);
            if(c1=='1') sb.append(teen[c2-'0']);
            else{
                if(c2=='0') sb.append(shi[c1-'0'-2]);
                else{
                    sb.append(shi[c1-'0'-2]).append(" ").append(ge[c2-'0'-1]);
                }
            }
        }
        switch(i){
            case 0: break;
            case 1: sb.append(" ").append("thousand ");break;
            case 2: sb.append(" ").append("million ");break;
            case 3: sb.append(" ").append("billion ");break;
            default: ;
        }
        return sb.toString();
    }
}

发表于 2021-08-05 22:41:14 回复(0)
对输入的数据进行切片处理。通过所有测试用例

#include<iostream>
#include<string>

using namespace std;
string g_strNum[] = { "zero","one","two","three","four","five","six","seven","eight",
                      "nine","ten","eleven","twelve","thirteen","fourteen",
                      "fifteen","sixteen","seventeen","eighteen","nighteen" };
string g_strTenDigit[] = { "twenty","thirty","forty","fifty","sixty","seventy",
                           "eighty","ninety" };
string g_strUnit[] = { "hundred","thousand","million","billion" };

string EnglishChange(const string& s)
{
    string tmp;
    if (s.empty())
        return tmp;
    int num = stoi(s);
    if (num < 20)
        tmp = g_strNum[num];
    else if (num < 100)
    {
        tmp = g_strTenDigit[num / 10 - 2];
        if (0 != num % 10)
            tmp += " " + g_strNum[num % 10];
    }
    else
    {
        if (100 == num)
            tmp = g_strNum[1] + " " + g_strUnit[0];
        else
        {
            tmp = g_strNum[num / 100] + " " + g_strUnit[0] + " and ";
            int iTen = num % 100;
            if (iTen < 20)
                tmp += g_strNum[iTen];
            else
            {
                tmp += g_strTenDigit[iTen / 10 - 2];
                if (0 != iTen % 10)
                    tmp += " " + g_strNum[iTen % 10];
            }
        }
    }
    return tmp;
}

int main()
{
    const int LEN_Split = 4;
    string strIn;
    while (cin >> strIn)
    {
        if (strIn.size() > 12)
            break;
        for (auto it = strIn.begin(); it != strIn.end(); ++it)
        {
            if (!isdigit(*it))  // 判断是否有非数字字符
            {
                cout << "error" << endl;
                return 0;
            }
        }
        string strSplit[LEN_Split];
        int index = 0;
        for (auto it = strIn.rbegin(); it != strIn.rend(); ++it)
        {
            if (strSplit[index / 3].empty())  // 三个一组
                strSplit[index / 3].push_back(*it);
            else
                strSplit[index / 3].insert(strSplit[index / 3].begin(), *it); // 插入前面
            ++index;
        }
        string strChange[LEN_Split];
        for (int i = 0; i < LEN_Split; ++i)
        {
            if (!strSplit[i].empty())
            {
                strChange[i] = EnglishChange(strSplit[i]);
            }
        }
        for (int i = LEN_Split - 1; i >= 0; --i)
        {
            if (!strChange[i].empty())
            {
                if (0 != i)
                    cout << strChange[i] << " " << g_strUnit[i] << " ";
                else
                    cout << strChange[i];
            }
        }
        cout << endl;
    }
    return 0;
}


发表于 2021-06-09 17:49:34 回复(0)
如果输入0,直接输出zero,正数进行递归处理:
(1) 对于1~19和整十的数字,直接进行枚举查找其英语表达。
(2) 不小于20的两位数,分别递归处理十位和个位。
(3) 对于不小于100且小于1000的数,整百直接通过百位数字来判断是几百就行;其他情况需要在几百后面跟上and,然后对低位再进行递归。
(4) "thousand", "million", "billion"三种情况均进行递归:以thousand为例,大于千位的部分(计算是几千)和小于千位的部分(对应(1)~(3)的情况)分别进行递归。
lt20 = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen seventeen eighteen nineteen".split()
tens = "twenty thirty forty fifty sixty seventy eighty ninety".split()

def trans(n):
    if n < 20:
        return lt20[n - 1: n]     # 小于20的直接查找枚举
    if n < 100:
        return [tens[n//10 - 2]] + trans(n % 10)    # 大于等于20小于100的,十位查枚举,个位递归继续查枚举
    if n < 1000:
        if n % 100 == 0:
            return [lt20[n // 100 - 1]] + ["hundred"]      # 整百处理
        return [lt20[n//100 - 1]] + ["hundred"] + ["and"] + trans(n % 100)
    for i, unit in enumerate(["thousand", "million", "billion"], 1):  # 这三个单位按10的3次方递增
        if n < pow(1000, i + 1):
            return trans(n // pow(1000, i)) + [unit] + trans(n % pow(1000, i))

while True:
    try:
        num = int(input())
        print(" ".join(trans(num)) if num > 0 else "zero")
    except:
        break

发表于 2021-04-02 13:17:05 回复(0)
看来我是学不会英语le
#include<iostream>
using namespace std;

string ones[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string tens[] = { "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nighteen" };
string twenties[] = { "zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety" };
int ihundreds[] = { 100, 1000, 1000000, 1000000000};
string hundreds[] = { "hundred", "thousand", "million", "billion" };

string iTostr(long long n)
{
    if(n>=0&&n<10)    {return ones[n];}
    else if(n>=10&&n<20)    {return tens[n%10];}
    else if(n>=20&&n<100)    {return twenties[n/10]+(n%10 ?" "+ ones[n%10]:"");}
    for(int i=0;i<3;i++)
    {
        if(n<ihundreds[i+1])    
        {
            return iTostr(n/ihundreds[i])+" "+hundreds[i]+(n%ihundreds[i]? (i? " ":" and ")+iTostr(n%ihundreds[i]):"");
        }
    }
    return "";
}

int main()
{
    long long n;
    while(cin>>n)
    {
        cout<<iTostr(n)<<endl;
    }
    return 0;
}


发表于 2021-03-18 16:24:07 回复(0)
写代码是体力劳动实锤了
import java.util.*;

public class Main{
    private static HashMap<Integer, String> map = new HashMap<Integer,String>();
    static{
        map.put(1,"one");    map.put(2,"two");
        map.put(3,"three");    map.put(4,"four");
        map.put(5,"five");    map.put(6,"six");
        map.put(7,"seven");    map.put(8,"eight");
        map.put(9,"nine");    map.put(10,"ten");
        map.put(11,"eleven");    map.put(12,"twelve");
        map.put(13,"thirteen");    map.put(14,"fourteen");
        map.put(15,"fifteen");    map.put(16,"sixteen");
        map.put(17,"seventeen");    map.put(18,"eighteen");
        map.put(19,"nineteen");    map.put(20,"twenty");
        map.put(30,"thirty");    map.put(40,"forty");
        map.put(50,"fifty");    map.put(60,"sixty");
        map.put(70,"seventy");    map.put(80,"eighty");
        map.put(90,"ninety");
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            long num = sc.nextLong();
            ArrayList<String> res = new ArrayList<String>();
            int cnt = 0;
            while(num != 0) {
                res.addAll(read((int)(num%1000)));
                num = num / 1000;
                if(num == 0) break;
                if(cnt == 0) {
                    res.add("thousand");
                }else if(cnt == 1) {
                    res.add("million");
                }else if(cnt == 2) {
                    res.add("billion");
                }
                cnt += 1;
            }
            for(int i = res.size() - 1; i >= 0; i--) {
                System.out.print(res.get(i) + " ");
            }
            System.out.println();
        }
    }
    
    private static List<String> read(int num) {
        ArrayList<String> list = new ArrayList<String>();
        int x = num % 100;
        if(x < 20 && x > 0) {
            list.add(map.get(x));
        }else if(x >= 20) {
            int g = x % 10;
            int s = x - g;
            if(g != 0) list.add(map.get(g));
            list.add(map.get(s));
        }
        int b = num / 100;
        if(b != 0){
            list.add("and");
            list.add("hundred");
            list.add(map.get(b));
        }
        return list;
    }
}


发表于 2021-03-06 15:42:21 回复(0)
while True:
    try:
        to19 = 'one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen seventeen eighteen nineteen'.split()
        tens = 'twenty thirty forty fifty sixty seventy eighty ninety'.split()

        num = input()
        n = len(num)
        def hundred(num):
            #print(num)
            ans = ''
            ten = num % 100
            num = num // 100
            if 0<ten < 20:
                ans = to19[ten-1]
            elif ten > 20 and ten % 10 != 0:
                ans = tens[(ten-20)//10] +' ' +to19[(ten%10)-1]
            else:
                ans = tens[(ten-20)//10]
            if num % 10 != 0:
                ans = to19[(num % 10)-1]+' ' +'hundred '+'and ' + ans
            return ans
        index = 0
        ans = ''
        pos = ['','thousand','million']
        while n-index*3-3>0:
            tmp = hundred(int(num[n-index*3-3:n-index*3]))
            ans = tmp+' '+ pos[index]+' ' + ans
            index += 1
        #print(index)
        tmp = hundred(int(num[:n-index*3]))
        ans = tmp + ' '+ pos[index]+' ' + ans
        print(ans)
    except:
        break
代码是这个样子的,想问问大家为什么不加while True,try和except就连输出都没有啊?
发表于 2020-08-18 18:58:38 回复(0)
c++ 直接转换,每三位的处理是相同的
#include <bits/stdc++.h>
using namespace std;
void trans(int num){//注意英文不要写错
    string a[9]={"one","two","three","four","five","six","seven","eight","nine"};
    string b[10]={"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninteen"};
    string c[8]={"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
    string d[2]={"hundred","and"};
    int k[3];
    for(int i=0;i<3;i++){
        k[i]=num%10;
        num=num/10;
    }
    if(k[2]!=0)
        cout<<a[k[2]-1]<<' '<<d[0]<<' '<<d[1]<<' ';
    if(k[1]==1)
        cout<<b[k[0]]<<' ';
    if(k[1]!=0&&k[1]!=1)
        cout<<c[k[1]-2]<<' ';
    if(k[0]!=0&&k[1]!=1)
        cout<<a[k[0]-1]<<' ';
}
int main(){
    string d[2]={"million","thousand"};
    long n;
    int m;
    while(cin>>n){
        m=n/1000000;//分段取出每三位
        if(m!=0){
            trans(m);
            cout<<d[0]<<' ';
        }
        m=n%1000000/1000;
        if(m!=0){
            trans(m);
            cout<<d[1]<<' ';
        }
        m=n%1000;
        trans(m);
        cout<<endl;//注意最后输出回车
    }
    return 0;
}

发表于 2020-08-17 17:47:13 回复(0)
// 测试用例通过90%,但感觉测试用例好像不太对,比如1538088
//答案输出:one million five hundred and thirty eight thousand eighty eight //程序输出:one million five hundred and thirty eight thousand and eighty eight(翻译软件也是这样的) #include <stdlib.h>
#include <stdio.h>
#include <string.h>

char* onePos[] = {"one", "two", "three", "four", "five", "six", \
                  "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",\
                 "fifteen", "sixteen", "seventee", "eighteen", "nineteen"};
char* tenPos[] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
void handleThreePos(int val, int flag) {
    int ten = val % 100;
    int hun = val % 1000 / 100;
    if(flag) printf(" ");
    if(hun) {
        printf("%s hundred", onePos[hun - 1]);
    }
    if(ten && hun) printf(" and ");
    else if(ten && flag) printf("and ");
    if(ten > 19) {
        int tt = ten / 10;
        int tg = ten % 10;
        if(tg) {
            printf("%s %s", tenPos[tt - 2], onePos[tg - 1]);
        } else {
            printf("%s", tenPos[tt - 2]);
        }
    } else if(ten > 0) {
        printf("%s", onePos[ten - 1]);
    }
}
void do_thousand(int val) {
    if(val) {
        handleThreePos(val / 1000, 0);
        printf(" thousand");
        handleThreePos(val % 1000, 1);
    }
}
void do_millon(int val) {
    handleThreePos(val / 1000000, 0);
    printf(" million ");
    do_thousand(val % 1000000);
}
int main(void) {
    char num[10];
    while(scanf("%s", num) != EOF) {
        int val = atoi(num);
        int len = (int)strlen(num);
        if(len > 6) {
            do_millon(val);
        } else if(len > 3) {
            do_thousand(val);
        } else {
            handleThreePos(val, 0);
        }
        printf("\n");
    }
    return 0;
}

发表于 2020-07-23 07:54:13 回复(0)
leetcode 原题,不过leetcode中间没有and
import java.util.*;
public class Main {
    private static final String[] tens = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    private static final String[] less_than_20 = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    private static final String[] thousands = {"", "thousand", "million", "billion"};
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long num = sc.nextLong();
            System.out.println(translate(num));
        }
        sc.close();
    } 
    public static String translate(long num) {
        if (num == 0) {
            return "zero";
        }
        String res ="";
        int i = 0;
        while (num > 0) {
            if (num % 1000 != 0) {
                long curr = num % 1000;
                res = numToString(curr) + thousands[i] + " " + res;
            }
            num /= 1000;
            i++;
        }
        return res.trim();
    }
    public static String numToString(long num) {
        if (num == 0) {
            return "";
        } else if (num < 20) {
            return less_than_20[(int)num] + " ";
        } else if (num < 100) {
            return tens[(int)(num / 10)] + " " + numToString((int)(num % 10));
        } else {
            return less_than_20[(int)(num / 100)] + " hundred and " + numToString((int)(num % 100));
        }
    }
}


发表于 2020-07-23 01:28:52 回复(0)

#0是非法数据,因此用空格做占位符
s0_19  = ' one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighth nineteenth'.split(' ')
s20_90  = 'twenty thirty forty fifty sixty seventy eighty ninety'.split(' ')

def num2words(n):
    if n <= 0:
        return('error')
    elif n < 20:
        return(str(s0_19[n]))
    elif n < 100 and n%10 == 0: #整十处理
        return(str(s20_90[n//10 - 2]))        
    elif n < 100:
        return(str(s20_90[n//10 - 2]+' '+num2words(n%10))) 
    elif n < 1000 and n%100 == 0: #整百处理
        return(str(num2words(n//100)+' hundred'))
    elif n < 1000:
        return(str(num2words(n//100)+' hundred and '+num2words(n%100))) #三位数必带and
    elif n < 1000000 and n%1000%100 == 0:
        return(str(num2words(n//1000)+' thousand'))
    elif n < 1000000:
        return(str(num2words(n//1000)+' thousand '+num2words(n%1000))) #这里有缺陷,中间有零要拼接“and”,但是此处没考虑(如2020,但还是通过了),下同
    elif n < 1000000000 and n%1000000%1000 == 0:
        return(str(num2words(n//1000000)+' million'))
    elif n < 1000000000:
        return(str(num2words(n//1000000)+' million '+num2words(n%1000000)))
    else:
        return('error') 


while True:
    try:
        print(num2words(int(input())).strip())
    except:break


编辑于 2020-02-16 18:46:26 回复(0)
每3位单独处理,先处理后三位,中间三位处理完+thousand,前三位处理完+million,最后拼一块,处理特殊情况
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Scanner;
import java.util.logging.LoggingMXBean;

public class Main {

	public static HashMap<Long, String> ji = new LinkedHashMap<>();
	public static HashMap<Long, String> shiji = new LinkedHashMap<>();
	public static HashMap<Long, String> jishi = new LinkedHashMap<>();

	static {
		ji.put(0L, "zero");
		ji.put(1L, "one");
		ji.put(2L, "two");
		ji.put(3L, "three");
		ji.put(4L, "four");
		ji.put(5L, "five");
		ji.put(6L, "six");
		ji.put(7L, "seven");
		ji.put(8L, "eight");
		ji.put(9L, "nine");

		shiji.put(10L, "ten");
		shiji.put(11L, "eleven");
		shiji.put(12L, "twelve");
		shiji.put(13L, "thirteen");
		shiji.put(14L, "fourteen");
		shiji.put(15L, "fifteen");
		shiji.put(16L, "sixteen");
		shiji.put(17L, "seventeen");
		shiji.put(18L, "eighteen");
		shiji.put(19L, "nineteen");

		jishi.put(2L, "twenty");
		jishi.put(3L, "thirty");
		jishi.put(4L, "forty");
		jishi.put(5L, "fifty");
		jishi.put(6L, "sixty");
		jishi.put(7L, "seventy");
		jishi.put(8L, "eighty");
		jishi.put(9L, "ninety");
	}

	public static String hundred = "hundred";
	public static String thousand = "thousand";
	public static String million = "million";
	public static String billion = "billion";
	public static String and = "and";

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

		while (scanner.hasNext()) {
			try {
				long purpose = scanner.nextLong();
				if (purpose < 0) {
					System.out.println("error");
					continue;
				}
				if (purpose == 0) {
					System.out.println("zero");
				}

				String spurpose = purpose + "";
				if (spurpose.length() > 9) {
					System.out.println("error");
					continue;
				}
				String lastpart = sanweishu(purpose % 1000);

				if (purpose / 1000 > 0) {
					String th = sanweishu((purpose / 1000) % 1000);
					if (th.length() > 0) {
						lastpart = th + " " + thousand + " " + lastpart;
					}
				}

				if (purpose / 1000000 > 0) {
					lastpart = sanweishu((purpose / 1000000)) + " " + million + " " + lastpart;
				}

				System.out.println(lastpart);

			} catch (Exception e) {
				System.out.println("error");
			}

		}

		scanner.close();
	}

	public static String sanweishu(long l) {
		if (l == 0) {
			return "";
		}
		StringBuilder sBuilder = new StringBuilder();
		long last1 = l % 10;
		long last2 = l % 100;
		long first = l / 100;
		long second = (l / 10) % 10;
		if (first != 0) {
			sBuilder.append(ji.get(first)).append(" ").append(hundred).append(" ");
		}
		if (last2 != 0) {
			if (sBuilder.length() > 0) {
				sBuilder.append(and).append(" ");
			}
			if (second == 0) {
				sBuilder.append(ji.get(last1));
			} else if (second == 1) {
				sBuilder.append(shiji.get(last2));
			} else {
				if (last1 == 0) {
					sBuilder.append(jishi.get(second));
				} else {
					sBuilder.append(jishi.get(second)).append(" ").append(ji.get(last1));
				}

			}
		}
		return sBuilder.toString().trim();
	}
}

发表于 2020-02-10 22:45:02 回复(0)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


char index_units[10][16] = {
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
};

char index_ten[10][16] = {
    "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};

char index_tens[10][16] = {
    "heihei", "heihei", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};


char *parse_2(int num)
{
    int n;
    char res[100];
    char *p;

    if(0<=num && num<10) {
        strcpy(res, index_units[num]);
        n = strlen(res);
    } else if(10<=num && num<20) {
        strcpy(res, index_ten[num-10]);
        n = strlen(res);
    } else if(20<=num && num<100) {
        strcpy(res, index_tens[num/10]);
        n = strlen(res);
        if((num%10) != 0) {
            res[n] = ' ';
            strcpy(res+n+1, index_units[num%10]);
            n = strlen(res);
        }
    } else {
        printf("parse_2: error input\n");
        while(1);
    }

    p = (char *)malloc(n+1);
    strcpy(p, res);
    return p;
}

char *parse_3(int num)
{
    int n;
    char res[100];
    char *p;

    if(0<=num && num<100) {
        p = parse_2(num);
        strcpy(res, p);
        free(p);
        n = strlen(res);
    } else if(100<=num && num<1000) {
        strcpy(res, index_units[num/100]);
        n = strlen(res);
        res[n] = ' ';
        strcpy(res+n+1, "hundred");
        n = strlen(res);
        if(num%100 != 0) {
            res[n] = ' ';
            strcpy(res+n+1, "and ");
            n += 5;
            p = parse_2(num%100);
            strcpy(res+n, p);
            free(p);
            n = strlen(res);
        }
    } else {
        printf("parse_3: error input\n");
        while(1);
    }

    p = (char *)malloc(n+1);
    strcpy(p, res);
    return p;
}

char *parse(int num)
{
    int nn;
    int tmp;
    char *p;

    int n;
    char res[100];

    nn = 0;
    tmp = num;
    while(tmp) {
        nn++;
        tmp /= 10;
    }
    if(nn == 0) {
        strcpy(res, "zero");
        n = strlen(res);
    } else if(1<=nn && nn<=3) {
        p = parse_3(num);
        strcpy(res, p);
        free(p);
        n = strlen(res);
    } else if(4<=nn && nn<=6) {
        p = parse_3(num/1000);
        strcpy(res, p);
        free(p);
        n = strlen(res);
        res[n] = ' ';
        strcpy(res+n+1, "thousand");
        n = strlen(res);
        if(num%1000) {
            res[n] = ' ';
            p = parse_3(num%1000);
            strcpy(res+n+1, p);
            free(p);
            n = strlen(res);
        }
    } else if(7<=nn && nn<=9) {
        p = parse_3(num/1000000);
        strcpy(res, p);
        free(p);
        n = strlen(res);
        res[n] = ' ';
        strcpy(res+n+1, "million");
        n = strlen(res);
        if((num%1000000)/1000) {
            res[n] = ' ';
            p = parse_3((num%1000000)/1000);
            strcpy(res+n+1, p);
            free(p);
            n = strlen(res);
            res[n] = ' ';
            strcpy(res+n+1, "thousand");
            n = strlen(res);
        }
        if((num%1000000)%1000) {
            res[n] = ' ';
            p = parse_3((num%1000000)%1000);
            strcpy(res+n+1, p);
            free(p);
            n = strlen(res);
        }
    }
    p = (char *)malloc(n+1);
    strcpy(p, res);
    return p;
}


int main()
{
    int n;
    int res;
    char *p;

    while(1) {
        res = scanf("%d", &n);
        if(res == EOF)
            break;

        p = parse(n);
        printf("%s\n", p);
        free(p);
    }
}

发表于 2018-05-23 12:28:55 回复(0)