题目描述
有一个非负整数,请编写一个算法,打印该整数的英文描述。
给定一个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;
}