这是一道细节题,没有什么思维量,但是写的时候要小心空格问题和零的处理。
代码如下:
class Solution {
public:
string threeDigit(int num, map<int,string>& mp)
{
string str="";
if(num==0) return str;
if(num>=100)
{
str+=mp[num/100]+" "+"Hundred"+" ";
num-=num/100*100;
}
if(num==0) return str;
if(num<=20) return str+mp[num]+" ";
str+=mp[num/10*10]+" ";
num-=num/10*10;
if(num!=0) str+=mp[num]+" ";
return str;
}
string numberToWords(int num) {
if(num==0) return "Zero";
map<int,string> Digit={{0,""},{1,"Thousand"},{2,"Million"},{3,"Billion"}};
map<int,string> mp={{1,"One"},{2,"Two"},{3,"Three"},{4,"Four"},{5,"Five"},
{6,"Six"},{7,"Seven"},{8,"Eight"},{9,"Nine"},{10,"Ten"},{11,"Eleven"},
{12,"Twelve"},{13,"Thirteen"},{14,"Fourteen"},{15,"Fifteen"},{16,"Sixteen"},
{17,"Seventeen"},{18,"Eighteen"},{19,"Nineteen"},{20,"Twenty"},{30,"Thirty"},
{40,"Forty"},{50,"Fifty"},{60,"Sixty"},{70,"Seventy"},{80,"Eighty"},{90,"Ninety"}};
vector<int> nums;
int cnt=0,now=0;
while(num)
{
now+=(num%10)*pow(10,cnt);
num/=10;
cnt++;
if(cnt==3)
{
nums.push_back(now);
cnt=0;
now=0;
}
}
if(now) nums.push_back(now);
string res;
int n=nums.size();
for(int i=n-1;i>=0;i--)
{
string str=threeDigit(nums[i],mp);
if(str!="")
res+=str+Digit[i]+" ";
}
int k=res.size()-1;
while(k>=0&&res[k]==' ') k--;
return res.substr(0,k+1);
}
};
网友评论