程序员面试金典——17.7数字发音
Solution1:我的答案。要AC这道题真不容易。。。细节注意太多
class ToString {
public:
vector<string> Digit = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
vector<string> Digit_teen = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> Digit_ten = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
vector<string> Digit_big = {"Hundred", "Thousand", "Million", "Billion"};
string toString(int x) {
// write code here
string res;
int Billion = x/1000000000;
int Million = (x%1000000000)/1000000;
int Thousand = (x%1000000)/1000;
int Hundred = x%1000;//三位数以下的数字
if(Billion != 0)
res += Num_to_Str(Billion) + " " + Digit_big[3];
if(Million != 0) {
if(res != "")
res += "," + Num_to_Str(Million) + " " + Digit_big[2];
else
res += Num_to_Str(Million) + " " + Digit_big[2];
}
if(Thousand != 0) {
if(res != "")
res += "," + Num_to_Str(Thousand) + " " + Digit_big[1];
else
res += Num_to_Str(Thousand) + " " + Digit_big[1];
}
if(Hundred != 0) {
if(res != "")
res += "," + Num_to_Str(Hundred);
else
res += Num_to_Str(Hundred);
}
return res;
}
//把三位数以内的数字转化为英文
string Num_to_Str(int x) {
string temp;
int a = x/100;//百位上的数字
int b = x%100;//百位以下的数字大小
int c = x%10; //个位数字
if(b != 0) {
if(b < 20) {
if(b < 10)
temp = Digit[b];
else
temp = Digit_teen[b%10];
}
else {
if(b%10 != 0)
temp = Digit_ten[b/10] + " " + Digit[b%10];
else
temp = Digit_ten[b/10];
}
}
if(a != 0) {
if(temp != "")
temp = Digit[a] + " " + Digit_big[0] + " " + temp;
else
temp = Digit[a] + " " + Digit_big[0];
}
return temp;
}
};