数字发音

题目描述

有一个非负整数,请编写一个算法,打印该整数的英文描述。

给定一个int x,请返回一个string,为该整数的英文描述。

测试样例:

1234

返回:"One Thousand,Two Hundred Thirty Four"

 

#include<bits/stdc++.h>
using namespace std;
string X[10] = {" ", "One", "Two","Three","Four","Five","Six","Seven","Eight","Nine"};
string OneX[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
string XZero[10] = {" ", " ", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string Hundred = "Hundred";
string Thousand = "Thousand";
string Million = "Million";
string Billion = "Billion";

class ToString {
public:
    string toString(int x) {
        // write code here
        string ans = "";
        int one = x / 1000000000;
        if(one != 0)
        ans += ChangeToWords(one) + " " +Billion;
        int two = (x % 1000000000) / 1000000;
        if(two != 0)
        {
            if(one != 0)
                ans += ",";
            ans +=ChangeToWords(two) + " " + Million;
        }
        int three = (x % 1000000) / 1000;
        if(three != 0)
        {
            if(two != 0)
                ans += ",";
            ans +=ChangeToWords(three) + " " + Thousand;
        }
        int four  = x % 1000;
        if(four != 0)
        {
            if(three != 0)
                ans += ",";
            ans += ChangeToWords(four);
        }
        return ans;
    }

    string ChangeToWords(int x)
    {
        string temp = "";
        int one = x / 100;
        if(one != 0)
        {
            temp = temp + X[one] + " " + Hundred;
        }
        int two = (x % 100) / 10;
        if(two >= 2)
        {
            if(one != 0)
                temp += " ";
            temp += XZero[two];
            int three =  x % 10;
            if(three != 0)
                temp += " " + X[three];
        }
        else if(two >= 1)
        {
            if(one != 0)
                temp += " ";
            int three =  x % 10;
            temp += OneX[three];
        }
        else if(two == 0)
        {
            int three =  x % 10;
            if(one != 0 && three != 0)
                temp += " ";
            if(three != 0)
                temp += X[three];
        }
        return temp;
    }
};

int main()
{
    ToString t;
    cout << t.toString(1234) << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值