项目欧拉#17错误答案

时间:2014-07-31 10:23:00

标签: java compiler-optimization

  

如果数字1到5用文字写出:一,二,三,四,   五,然后共有3 + 3 + 5 + 4 + 4 = 19个字母。

     

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

     

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

我的代码在

下面
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 个答案:

答案 0 :(得分:2)

问题在于你的百模运算,在它当前的形状中,它正在评估115onehundredandtenfive这里错误的是修改过你的问题的逻辑部分

    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];
    }

你缺少中间条件(否则如果)。

相关问题