所以,我正在研究proj euler 8并最终感到沮丧和欺骗。我看到我发现https://github.com/nayuki/Project-Euler-solutions/blob/master/java/p008.java的答案与我使用不同代码的方式相同,但只要我得到不同的答案。
所以我改变了行并开始复制他的代码以查看缺陷的位置,但最终,当我改变所有内容并使我的代码与他的代码完全相同(使用不同的变量名称)时,我仍然得到了不同的答案。有人可以向我解释为什么会这样吗?第一个是我的代码,第二个是他的代码。
public class Attempt {
public static void main (String[] args) {
System.out.println(new Attempt().getAnswer());
}
private static final String BIG_NUMBER = "I copied and pasted his number here, so no difference. I won't write it out since it's 1000 digits."
private static final int ADJACENT = 13;
public String getAnswer() {
long highest = -1;
for (int i = 0; i + ADJACENT <=BIG_NUMBER.length(); i++ ) {
long currentProduct = 1;
for (int thirteen = 1; thirteen < ADJACENT; thirteen++)
currentProduct *= BIG_NUMBER.charAt(i + thirteen) '0';
highest = Math.max(currentProduct, highest);
}
return Long.toString(highest);
}
}
public class Cheat {
public static void main(String[] args) {
System.out.println(new Cheat().run());
}
private static final String NUMBER = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801$
private static final int ADJACENT = 13;
public String run() {
long maxProd = -1;
for (int i = 0; i + ADJACENT <= NUMBER.length(); i++) {
long prod = 1;
for (int j = 0; j < ADJACENT; j++)
prod *= NUMBER.charAt(i + j) - '0';
maxProd = Math.max(prod, maxProd);
}
return Long.toString(maxProd);
}
}
答案 0 :(得分:1)
您的代码:
for (int thirteen = 1; thirteen < ADJACENT; thirteen++) // Not 0 based
currentProduct *= BIG_NUMBER.charAt(i + thirteen) '0'; // Error
应改为:
for (int thirteen = 0; thirteen < ADJACENT; thirteen++)
currentProduct *= BIG_NUMBER.charAt(i + thirteen)- '0';
PS:int thirteen
听起来像是一个常数,而是使用更好的名字。
答案 1 :(得分:1)
Java String
(s)和数组从0
开始(不是1
)。
for (int thirteen = 0; thirteen < ADJACENT; thirteen++)
或(我假设您在错过下面的'0'减号时出现了印刷错误)
currentProduct *= BIG_NUMBER.charAt(i + thirteen - 1) - '0';
注意 i + thirteen - 1
。此外,您的变量名thirteen
似乎没有j
那么具有描述性......至少我不会想到j
始终等于13
。