【问题标题】:Project Euler #17 wrong answerProject Euler #17 错误答案
【发布时间】:2014-07-31 10:23:00
【问题描述】:

如果数字 1 到 5 用文字写出:一、二、三、四、 5,那么总共使用了 3 + 3 + 5 + 4 + 4 = 19 个字母。

如果从 1 到 1000(包括一千)的所有数字都是 用文字写出来,用多少个字母?

注意:不要计算空格或连字符。例如,342(三百 和四十二)包含23个字母和115(一百一十五) 包含 20 个字母。在写出数字时使用“and” 符合英国的使用习惯。

我的代码在下面

public class ProjectEuler17 {
public static String[] ones = { "", "one", "two", "three", "four", "five",
    "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
    "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
    "eighteen", "nineteen" };

public static String[] tens = { "", "ten", "twenty", "thirty", "forty",
    "fifty", "sixty", "seventy", "eighty", "ninety" };

public static String[] hundreds = { "", "onehundred", "twohundred",
    "threehundred", "fourhundred", "fivehundred", "sixhundred",
    "sevenhundred", "eighthundred", "ninehundred", "oneThousand" };

public static void main(String[] args) {
    System.out.println(run());
}

public static String run() {
    int sum = 0;
    for (int i = 1; i <= 1000; i++)
        sum += convertToWord(i).length();
    return Integer.toString(sum);
}

public static String convertToWord(int n) {
    int unit=n%10;
    int tensdivide = (n / 10)%10;
    int hundreadsdivide = n / 100;
    int hundredModulo=n%100;
    if (n <= 19) {
        //under 20(exclusive)
        return ones[n];
    } else if (n < 100 && n > 19) {
        //from 20 to 100(exclusive)
        return tens[tensdivide] + ones[unit];
    } else {
        /* 100,200,300,400,500 ...1000("onehundred", "twohundred","threehundred", "fourhundred", "fivehundred", "sixhundred",
        "sevenhundred", "eighthundred", "ninehundred", "oneThousand") */

        if(hundredModulo == 0){
                return hundreds[hundreadsdivide] +tens[tensdivide] + ones[unit];
        }else{
            //one hundred and tewnty
            return hundreds[hundreadsdivide] +"and" +tens[tensdivide] + ones[unit];
        }

    }
}

我得到的答案类似于 21088,这是错误的正确答案是: 21124 如果你发现一些错误,请帮助我,也建议我如何让我的代码更快。

【问题讨论】:

  • +1 有趣的问题,好好尝试。
  • 你是如何计算出21124 的?你检查过数组中字符串的拼写吗?
  • @Ninad Pingale - 首先我得到 21125。然后我将该答案输入到 Euler 站点。它不正确,所以我在网上查了一下。并且知道正确答案是 21124

标签: java compiler-optimization


【解决方案1】:

问题在于您的百模运算,在其当前状态下,它正在评估 115 到 onehundredandtenfive 这是错误的,这是应该解决您问题的修改后的逻辑部分

    if(hundredModulo == 0){
            return hundreds[hundreadsdivide] +tens[tensdivide] + ones[unit];
    }else if (hundredModulo <20) {
        return hundreds[hundreadsdivide] +"and" + ones[hundredModulo];
    } else {
        //one hundred and tewnty
        return hundreds[hundreadsdivide] +"and" +tens[tensdivide] + ones[unit];
    }

您缺少中间条件(else-if)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多