4

我一直在尝试解决 ProjectEuler 上的 P17(http://projecteuler.net/problem=17),但显然我遗漏了一些东西,因为我得到的答案(20908)更小。有人可以看看我的代码并告诉我吗?找了半个小时,还是看不到。

public class P17{
  public static void main(String[]args){
        //1, 2, 3... 9
        String[] a = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        int s1 = 0;
        for(String i: a){
            s1+=i.length();
        }

        //10, 11, 12... 19
        String[] b = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "eighteen", "nineteen"};
        int s2 = 0;
        for(String i: b){
            s2+=i.length();
        }

        //20, 30, 40... 90
        String[] c = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
        int s3 = 0;
        for(String i: c){
            s3+=i.length();
        }

        //21, 22, 23... 31, 32, 33... 99
        int s4 = 0;
        for(String i: c){
            for(String j: a){
                s4+=(i+j).length();
            }
        }

        String x = "hundred";
        String y = "onethousand";
        String z = "and";

        //100, 200, 300... 900
        int s5 = 0;
        for(String i: a){
            s5+=(i+x).length();
        }

        //101, 102, 103... 201, 202, 203... 909
        int s6 = 0;
        for(String i: a){
            for(String j: a){
                s6+=(i+x+z+j).length();
            }
        }

        //110, 111, 112... 210, 211, 212... 919
        int s7 = 0;
        for(String i: a){
            for(String j: b){
                s7+=(i+x+z+j).length();
            }
        }

        //120, 130, 140... 220, 230, 240... 990
        int s8 = 0;
        for(String i: a){
            for(String j: c){
                s8+=(i+x+z+j).length();
            }
        }

        //121, 122, 123... 221, 222, 223... 999
        int s9 = 0;
        for(String i: a){
            for(String j: c){
                for(String k: a){
                    s9+=(i+x+z+j+k).length();
                }
            }
        }

        //sum
        int sum = s1+s2+s3+s4+s5+s6+s7+s8+s9+y.length();
        System.out.print(sum);
    }
}
4

1 回答 1

19
String[] b = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "eighteen", "nineteen"};

十七在哪里?

(有趣的是你在 Project Euler 问题17上犯了这个错误......)

于 2013-04-24T14:29:15.523 回答