[编程题]学英语

Talk is cheap, show me the code.

一、问题描述

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型整数

输出描述:

输出相应的英文写法

输入例子:

2356

输出例子:

two thousand three hundred and fifty six

二、问题分析

这道题就是字符串处理,但是很多细节需要注意,比如空格的问题,and的位置问题,单词的拼写问题。主要思路是,三位数三位数地处理。

#include <iostream>
#include <string>
using namespace std;

string convert(int n)
{
    string change[9] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    string ten[10] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen"};
    string a[8] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    int m = 0, s = 0, t = 0;
    m = n % 10;
    n = n / 10;
    if (n != 0)
        s = n % 10;
    n = n / 10;
    if (n != 0)
        t = n % 10;
    string str;
    if (t != 0)
        str = str + change[t - 1] + " hundred";
    if (s != 0 || m != 0)
    {
        if (t != 0)
            str = str + " and ";
        if (s == 1)
        {
            str = str + ten[m];
        } else if (s != 0) {
            str = str + a[s - 2];
        }
        if (s != 1 && m != 0)
        {
            if (s != 0)
                str = str + " " + change[m - 1];
            else
                str = str + change[m - 1];
        }
    }
    return str;
}

int main()
{
    long num;
    while (cin >> num)
    {
        int n1 = 0, n2 = 0, n3 = 0, n4 = 0;
        n1 = num % 1000;
        num = num / 1000;
        if (num != 0)
            n2 = num % 1000;
        num /= 1000;
        if (num != 0)
            n3 = num % 1000;
        num /= 1000;
        if (num != 0)
            n4 = num % 1000;
        string s;
        if (n4 != 0)
            s = s + convert(n4) + " billion ";
        if (n3 != 0)
            s = s + convert(n3) + " million ";
        if (n2 != 0)
            s = s + convert(n2) + " thousand ";
        s = s + convert(n1);
        cout << s << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值