解题思路
我们知道,每三位会出现一个千级以上单位,每三个间有个,百,十单位,则可以按照
num%1000 ,每三位数模拟,三位数后若num>0,则可以使用栈保存新进制(千,百万…)而此单位用一个长度len保存即可
代码
class Solution
{
public:
string numberToWords(int num)
{if(num==0)return "Zero";
int len = 2,p1,p2,p3,p4,p5,p6,p7,p8;
stack<string> s;
string result ="";
while (num)
{
p1 = num%1000;
p2 = p1%100;
p3 = p1/100;
if(0<p2&&p2<20)
s.push(Shift(p2));
else if(p2>=20)
{
p4 = p2%10;
p2/=10;
if(p4>0)
s.push(Shift(p4));
if(p2>0)
s.push(ShiftTy(p2));
}
if(p3>0)
{
s.push(ShiftUnit(1));
s.push(Shift(p3));
}
num/=1000;
if(num>0)
{ cout<<len;
if(len>2&&s.top()==ShiftUnit(len-1))
{
s.pop();
}
s.push(ShiftUnit(len++));
}
}
while (!s.empty())
{
if(s.size()==1)
{
result+=s.top();
return result;
}
result += s.top()+" ";
s.pop();
}
return result;
}
string ShiftUnit(int num)//百,千,百万
{
string nums[]{"","Hundred","Thousand","Million","Billion"};
return nums[num];
}
string ShiftTy(int num)//十位
{
string nums[]{"", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
return nums[num - 1];
}
string Shift(int num)//1-20
{
string nums[]{"", "One", "Two",
"Three", "Four", "Five","Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
return nums[num];
}
};