有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Project Euler#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.

我的代码在下面

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

    }
}

I am getting answer like 21088 which is wrong The Correct Answer is : 21124 Help me if u find some thing wrong also suggest me how to make my code faster.


共 (1) 个答案

  1. # 1 楼答案

    问题在于你的百模运算,在它当前的状态下,它正在计算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];
        }
    

    你错过了中间条件(否则如果)