gpt4 book ai didi

java - 得到错误的结果 - Java

转载 作者:行者123 更新时间:2023-11-30 03:34:21 26 4
gpt4 key购买 nike

我正在尝试构建一个程序,它会告诉我 13 个相邻数字的乘积最高的乘积。然而,它总是给我错误的答案。这段代码有什么问题?

import java.lang.Character; 

public class ProjectEuler8 { public static void main(String[] args) {

String num = "73167176531330624919225119674426574742355349194934"+
"9698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511"+
"1254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113"+
"6222989342338030813533627661428280644448664523874930358907296290491560440772390713810515859307960866"+
"7017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243"+
"5258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482"+
"8397224137565705605749026140797296865241453510047482166370484403199890008895243450658541227588666881"+
"1642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142607690042"+
"2421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188"+
"8458015616609791913387549920052406368991256071760605886116467109405077541002256983155200055935729725"+
"71636269561882670428252483600823257530420752963450";

int NUM_LENGTH = num.length();

char[] number = new char[NUM_LENGTH];

for (int i=0; i<NUM_LENGTH; i++) { number[i] = num.charAt(i); }

int mult=0;
int highest=0;

for (int j=0; j<=987; j++) {
int a = number[j]; a=Character.getNumericValue(a);
int b = number[j+1]; b=Character.getNumericValue(b);
int c = number[j+2]; c=Character.getNumericValue(c);
int d = number[j+3]; d=Character.getNumericValue(d);


int e = number[j+4]; e=Character.getNumericValue(e);
int f = number[j+5]; f=Character.getNumericValue(f);
int g = number[j+6]; g=Character.getNumericValue(g);
int h = number[j+7]; h=Character.getNumericValue(h);
int i = number[j+8]; i=Character.getNumericValue(i);
int k = number[j+9]; k=Character.getNumericValue(k);
int l = number[j+10]; l=Character.getNumericValue(l);
int m = number[j+11]; m=Character.getNumericValue(m);
int n = number[j+12]; n=Character.getNumericValue(n);

mult = a*b*c*d*e*f*g*h*i*k*l*m*n;
if (mult > highest)
highest = mult;
System.out.println(highest);}

}}

最佳答案

代码对我来说看起来不错。它会给你一个循环大小 988 的列表。尽管你要检查每个循环中最高产品的打印值。我不知道你所说的“错误”答案是什么意思,我想知道你是否从这个函数输出的所有整数中挑出了答案。顺便说一句,这将是最后一篇。

建议:将最高的临时值存储在某个虚拟整数中,然后在循环外打印出来。

重构代码的空间很大,即您可以摆脱获取 char 数组的逻辑,并且当 13 位数字中的任何一个为 0 时,您可以无需整数乘法的计算开销。

关于java - 得到错误的结果 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336700/

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