您的位置:首页 > 其它

[273]Integer to English Words

2015-11-11 21:26 357 查看
【题目描述】

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"


Hint:
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

【思路】
这道题没啥难点,方法也在题目里提示了,就是把数据分成每三个数为一段来分别表示,但是有很多的边界数据,也就是说这道题要考虑比较全面。需要注意的地方有:

1.要判断输入的数是否为0,如果是0要显示

2.如果末尾段的数为0,则不显示(要处理相关的空格问题),中间段的数显示的时候其末尾也不要加空格

3.如果中间段的数为0,则不显示,同理也不要留空格

【代码】

class Solution {
public:
string word(int num){
string word1[11]={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
string word2[11]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
string word3[11]={"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
string ans;
if(num>=100){
if(num%100==0) ans=word1[num/100]+" Hundred";
else ans=word1[num/100]+" Hundred ";
}
num=num%100;
if(num<10&&num>=1){
ans=ans+word1[num];
}
else if(num>=10&&num<=19){
ans=ans+word2[num%10];
}
else if(num>=20&&num<=99){
if(num%10==0) ans=ans+word3[num/10-2];
else{
ans=ans+word3[num/10-2]+" ";
num=num%10;
ans=ans+word1[num];
}
}
return ans;
}
string numberToWords(int num) {
if(num==0) return "Zero";
string danwei[4]={"Thousand","Million","Billion"};
vector<int> group;
while(num>0){
group.push_back(num%1000);
num=num/1000;
}
//group.push_back(num);
int sz=group.size();
for(int i=0;i<sz;i++){
cout<<group[i]<<endl;
}
string ans;
bool flag=false;
if(group[0]!=0){
ans=word(group[0]);
flag=true;
}
for(int i=1;i<sz;i++){
if(group[i]==0) continue;
//else flag=true;
if(flag==false) ans=word(group[i])+" "+danwei[i-1];
else ans=word(group[i])+" "+danwei[i-1]+" "+ans;
flag=true;
}
return ans;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: