project euler 17 Number letter counts

来源:互联网 发布:linux dd命令安装系统 编辑:程序博客网 时间:2024/06/05 07:53

题目:

https://projecteuler.net/problem=17

题意:

Number letter counts
Problem 17

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.

把1~1000这1000个数字写成英语表达方式,求总共有多少字母,其中"and"要统计,但连接符和空格不统计

思路:

没啥好说的,模拟。写的时候脑袋瓦特了,找了好久bug。。。

代码:

#include <bits/stdc++.h>using namespace std;typedef long long ll;const int N = 1000 + 10;const char *num[N];void table(){    num[1] = "one";    num[2] = "two";    num[3] = "three";    num[4] = "four";    num[5] = "five";    num[6] = "six";    num[7] = "seven";    num[8] = "eight";    num[9] = "nine";    num[10] = "ten";    num[11] = "eleven";    num[12] = "twelve";    num[13] = "thirteen";    num[14] = "fourteen";    num[15] = "fifteen";    num[16] = "sixteen";    num[17] = "seventeen";    num[18] = "eighteen";    num[19] = "nineteen";    num[20] = "twenty";    num[30] = "thirty";    num[40] = "forty";    num[50] = "fifty";    num[60] = "sixty";    num[70] = "seventy";    num[80] = "eighty";    num[90] = "ninety";    num[100] = "hundred";    num[1000] = "thousand";    num[0] = "and";}int check(int x){    int cnt = 0, And = 0;    if(x == 1000)        cnt += strlen(num[x/1000]) + strlen(num[1000]);    else    {        if(x >= 100)//有百位数字            cnt += strlen(num[x/100]) + strlen(num[100]);        if(x/100 != 0 && x%100 != 0)//百位和十位或者各位存在,需要加个and            cnt += strlen(num[And]);        x %= 100;//去掉百位数字        if(x != 0)        {            if(x < 20)//小于20,有专用数字,                cnt += strlen(num[x]);            else            {                if(x%10 == 0)//只有十位数字没有个位数字                    cnt += strlen(num[x]);                else//十位和个位数字都有                    cnt += strlen(num[x-x%10]) + strlen(num[x%10]);            }        }    }    return cnt;}int main(){    table();    cout << check(21) << endl;    int ans = 0;    for(int i = 1; i <= 1000; ++i)    {        int temp = check(i);        //printf("%d %d\n", i, temp);        ans += temp;    }    printf("%d\n", ans);    return 0;}
原创粉丝点击