zoukankan      html  css  js  c++  java
  • projectEuler 17

    将1……n的数表示成英文,求表示成这些英文的字母的和

    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-19直接替换,然后20,30,40,50,60,70,80,90均有一个英文字符

    当数字超过100且不是整数时,需要加上hundred和and10个字母

    当数字超过100是整数时,值家hundred7个字母

    当数字是1000时,直接的one thousand11个字母

    如果有耐心,可以好好的统计规律,求和的时候都不需要迭代,可以一次计算出这个值,我没有那么多耐心,还是老老实实的循环

    private static int[] num_letters = { 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8,
                8, 7, 7, 9, 8, 8, 6, 6, 5, 5, 5, 7, 6, 6 };
    
        private static int numLetters(int N) {
            int result = 0, hun = N / 100 % 10, ten = N / 10 % 10, sin = N % 10;
            if (hun > 0) {
                result += num_letters[hun - 1] + 7; // 等于个位数hundred
                if (ten > 0 || sin > 0)
                    result += 3;// 如果不是整百需加上'and'
            }
            if (ten == 1) {
                result += num_letters[9 + sin];
            } else {
                if (ten > 1)
                    result += num_letters[17 + ten];
                if (sin > 0)
                    result += num_letters[sin - 1];
            }
    
            return result;
        }
    
        private static int sumLetters(int N) {
            int result = 0;
            if (N == 1000) {
                result += 11;
                N--;
            }
            for (int i = 1; i <= N; i++) {
                result += numLetters(i);
            }
    
            return result;
        }
    View Code
  • 相关阅读:
    关于c:fakepath的解决办法
    golang channel 源码剖析
    深入虚拟内存(Virtual Memory,VM)
    浅析 golang module
    浅析 golang interface 实现原理
    Golang channel实现
    LCS(最长公共字序列)实现
    Golang令牌桶-频率限制
    OpenGL(3)-三角形
    OpenGL(2)-窗口
  • 原文地址:https://www.cnblogs.com/lake19901126/p/3102631.html
Copyright © 2011-2022 走看看