首先我们观察到1-1000这些数字英文表示存在规律,例如121为 one hundred and twenty-one可分为one hundred and+ twenty+one,因此我们在记录数字英文表示的时候,只需要知道个位,十位和百位的数字就行。接下来需要特殊处理的数字有1-19,20,30直到90。数字处理如下:
定义一个数组
string m[20]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}
string n[10]={"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
算法:
- 初始处理:(其中1<= i < 1000)
a=i%10;//个位数字
b=(i%100)/10;//十位
c=i/100;//百位
- 循环开始1<= i < 1000
- 如果i%100==0,three=m[c]+7,否则,three=m[c].Length()+7+3;
- 如果b==1,sencond=m[b],first=0,否则,second=n[b].Length(),first=m[a].Length();
- sum=first+second+three;
- 循环结束
程序代码:
#include <IOSTREAM>
#include <CSTRING>
using namespace std;
const string m[20]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
const string n[10]={"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
int main()
{
int first,second,three,sum=0;
for (int i=1;i<1000;++i)
{
int a=i%10;//个位数字
int b=(i%100)/10;//十位
int c=i/100;//百位
if(c >= 1)
{
three = m[c].length() + 7;
if(i % 100 != 0)
three += 3;
}
else
three = 0;
if(b >= 2)
{
second = n[b].length();
first = m[a].length();
}
else
{
second = 0;
first = m[i % 100].length();
}
sum = sum + first + second + three;
}
sum+=11;
cout<<sum<<endl;
return 0;
}