Java Foo-Bar挑战测试用例失败
现在我正在进行Foo-Bar挑战,我已经接近3级了。唯一阻止我的是我无法确定的单一案例失败。有人知道为什么这个代码会失败吗 期望的结果:如果我有一个数组,比如int[]x={1,4,1};程序应该得到这个数组的子集,并找到其和为3的最大倍数的子集,然后以最大整数组合返回子集 发生了什么事?:Google Foo.Bar给了我 测试一通过! 测试2通过了! 测试3通过了! 测试4通过了! 测试5失败 我想知道是什么情况导致此代码失败。 目的如下: 你有L,一个包含一些数字(0到9)的列表。写一个函数答案(L),它可以从这些数字中的一些或所有数字中找出最大的数字,并且可以被3整除。如果无法生成这样的数字,请返回0作为答案。L将包含1到9位数字。同一数字可能在列表中出现多次,但列表中的每个元素只能使用一次 以下是我的代码,可能比较冗长,可以用更简单的方式完成:Java Foo-Bar挑战测试用例失败,java,arrays,subset,Java,Arrays,Subset,现在我正在进行Foo-Bar挑战,我已经接近3级了。唯一阻止我的是我无法确定的单一案例失败。有人知道为什么这个代码会失败吗 期望的结果:如果我有一个数组,比如int[]x={1,4,1};程序应该得到这个数组的子集,并找到其和为3的最大倍数的子集,然后以最大整数组合返回子集 发生了什么事?:Google Foo.Bar给了我 测试一通过! 测试2通过了! 测试3通过了! 测试4通过了! 测试5失败 我想知道是什么情况导致此代码失败。 目的如下: 你有L,一个包含一些数字(0到9)的列表。写一个函
public class Answer {
public static int answer(int[] l) {
int n = l.length;
int sum = 0;
int max =0;
int fragment = 0;
// Run a loop to get all subsets of an Array
for (int i = (1<<n)-1; i > 0; i--)
{
// Current subset
for (int j = 0; j < n; j++)
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0) {
sum+=l[j]; //Add the numbers of the subset together
fragment = 10*fragment + l[j]; //Get the numbers used to get the sum
}
//Taking Advantage of the divisible rules of 3, if the sum of a subset is a multiple of 3
if(sum%3 == 0) {
//Update the max multiple
if (max<fragment) {
max = fragment;
}
}
sum=0;
fragment = 0;
}
//Rearrange the max number order.
return getLargestNumber(max);
}
//Function to reaarange an integer to it's greatest combination
private static int getLargestNumber(int input) {
int[] numbers = new int[10];
for(int i = input; i != 0; i /= 10) {
numbers[i % 10]++;
}
int counter = 0;
long result = 0;
for (int i = 0; i < 10; counter += numbers[i++]) {
result += (int)((Math.pow(10, numbers[i]) * i - 1) / 9)
* Math.pow(10, counter);
}
return (int)result;
}
}
公共类答案{
公共静态int应答(int[]l){
int n=l.长度;
整数和=0;
int max=0;
int片段=0;
//运行循环以获取数组的所有子集
对于(int i=(1)你有没有尝试过最简单的“算法”,也就是说,你对列表排序,对列表中的所有成员求和,然后每次都弹出最小的元素,直到你达到0或一个可以被3整除的数字?@asettouf我想我没有完全理解你的意思。好像我说had int j[]={4,3,5,1},把它排序为{5,4,3,1}如果我达到0或者总和等于一个可以被3整除的数字,那么就说1?欢迎来到Stack Overflow!寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现问题所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:。我认为您的代码有效…您能在失败的地方提供输入吗?@YossiVainshtein这就是问题所在,我找不到任何问题。唯一的问题是我能想到的是,变量片段远远超出了int极限,导致max依次输出一个负数。这种情况是int[]l={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8};