gpt4 book ai didi

java - 试图找出我在 Project Euler Q8 上搞砸的地方

转载 作者:行者123 更新时间:2023-12-01 09:36:02 34 4
gpt4 key购买 nike

所以我试图从 Project Euler Question 8 中解决这个问题。我写了一些我认为相当不错的东西,并花了我一些时间来思考它。如果我输入给定的测试用例,我会返回正确的答案,但是当我尝试 13 时,我得到的答案是错误的..我不知道我在哪里搞砸了。当我输入 13 时,我很乐意发布我想要的结果,但这就是我试图回答的问题。无论如何,我当前的输出是 8,821,658,160

@SuppressWarnings("null")
private static double largestProductSeries(String series, int num) {
double max = 0;
double temp = 1;
int nextNum;
int[] numbers = new int[num];

//emtpy string checks
if (series.length() == 0) {
return (Double) null;
}

//Initially fill array
for (int m = 0; m < num; m++) {
temp *= (numbers[m] = Character.getNumericValue(series.charAt(m)));
}

for (int i = num-1; i < series.length()-1; i++) {
if (temp > max) {
//System.out.println("Found Max: " + Arrays.toString(numbers));
max = temp;
}
System.out.println("Eval: " + Arrays.toString(numbers));
nextNum = Character.getNumericValue(series.charAt(i + 1));

//Zero Optimization by skipping over zeros
if (nextNum != 0) {
temp = (temp / numbers[0]) * nextNum;

for (int j = 0; j < num-1; j++){
numbers[j] = numbers[j+1];
}
numbers[num-1] = nextNum;
} else {
temp = 1;
i = getNextIndex(series, i+2, num);

if (i == -1) {
break;
}

for (int j = i, k = 0; j < num+i; j++, k++) {
temp *= (numbers[k] = Character.getNumericValue(series.charAt(j)));
}

i = i + (num - 1);
}
}
return max;
}

/**
* Gets next staring index of number series to evaluate
* @param series String of numbers
* @param index Current index to start looking
* @param num size of multiplied series
* @return Index where the next series should begin with Returns -1 if out of bounds
*/
private static int getNextIndex(String series, int index, int num) {
if (index >= series.length() - num) {
return -1;
}

String temp = series.substring(index, index + num);
if (temp.contains("0")) {
return getNextIndex(series, temp.lastIndexOf('0') + 1 + index, num);
}
return index;
}

最佳答案

我不知道你到底哪里搞砸了,但我发现你的解决方案过于复杂。检查我的 C# 解决方案,看看是否有帮助。解决方案是23514624000

private static long findMax(string series, int howMany)
{
var numbers = series.Select(c => int.Parse(c.ToString())).ToArray();

var highest = 0L;

for (int i = 0; i < numbers.Count() - howMany; i++)
{
var result = 1L;
for (int j = i; j < i + howMany; j++)
{
result *= numbers[j];
}

if (result > highest)
highest = result;
}

return highest;
}

关于java - 试图找出我在 Project Euler Q8 上搞砸的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919847/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com