[編程題]學英語

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章