Chinaunix首页 | 论坛 | 博客
  • 博客访问: 216506
  • 博文数量: 68
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 715
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-08 09:53
文章分类
文章存档

2012年(29)

2011年(3)

2010年(18)

2009年(18)

我的朋友

分类: C/C++

2012-01-25 17:05:32

问题:

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?


NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

答案:21124

#include

const int singleWord[20] =
{ 4, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6,  6, 8, 8, 7, 7, 9, 8, 8 }; 
const int tensPlaceWord[10] = { 0, 0, 6, 6, 5, 5, 5, 7, 6, 6 }; 
const int hunWord = 7;
const int thouWord = 11;

int countLetters (int num)
{
    int count = 0; 
    if (num == 1000) { 
        return thouWord; 
    } 

    if (num / 100 > 0) { 
        count += singleWord[num / 100] + hunWord; 
        if (num % 100 > 0) { 
            count += 3; 
        } 
    } 

    if (num % 100 >= 20) { 
        // sb.append(tensPlace[num / 10 % 10]); 
        count += tensPlaceWord[num / 10 % 10]; 
        if (num % 10 > 0) { 
            // sb.append(" " + single[num % 10]); 
            count += singleWord[num % 10]; 
        } 
    } else if (num % 100 > 0) { 
        // sb.append(single[num % 100]); 
        count += singleWord[num % 100]; 
    } 
    return count; 



int main(void)
{
    int result=0; 
    for(int i=1;i<=1000;i++) 
    { 
        result+=countLetters(i); 
    } 

    printf("The result is %d\n", result);

    return 0;
}



阅读(926) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~