最近,當我嘗試解決一個問題時,我給出了0到9之間的一些數字,並且必須找到可分割的最大整數通過3.無法找到測試用例,我的程序找到可被3整除的最大整數出錯
我已經讀過我的代碼,但我無法找到測試用例失敗的地方。如果堆棧溢出的優秀人員能夠幫助我找到測試用例,我將不勝感激。測試用例是一個隱藏的測試用例,所以我不能只打印測試用例的元素。
import java.util.Arrays;
import java.util.LinkedList;
public class Main {
public int answer(int[] l) {
int b[] = new int[l.length];
int divb = 0;
int div = 0;
int t = 0;
int mi = 1;
int counter = 0;
LinkedList<Integer> ab = new LinkedList<Integer>();
Arrays.sort(l);
for (int i = 0; i < l.length; i++) {
ab.add(l[i]); //adding the elements to linkedlist after sorting them
div += l[i]; //adding all the elements in the array
b[i] = l[i] % 3;//we use b[i] to find whether we have 0,1,2 as one of the remainders
divb += b[i];
if (b[i] == 2) {
mi = 0;
}
if (b[i] == 1) {
counter = 1;
}
}
if (div % 3 == 1) {
if (counter == 1) {/*if counter is 1 that means we have atleast one element which has remainder 1 where we can remove that element to get a an integer in descending order of its digits which are divisible by 3*/
for (int i = 0; i < l.length; i++) {
if (b[i] == 1) {
div -= l[i];
ab.remove(i);
break;
}
}
} else {//if there is no such digit with remainder 1 but we have a number like 3,6,9 which is divible by 3 then we should return such a number.
int tk = 0;
for (int i = 0; i < l.length; i++) {
if (b[i] != 0) {
div-=l[i];
ab.remove(tk);
tk--;
}
tk++;
}
}
if (div % 3 != 0) {
return 0;
}
}
int k[] = new int[2];
if (div % 3 == 2) {//if the remainder is 2 then we have to remove oen digit with remainder as 2 or two digits with remainder as one. I tried to use various counters so that they don't effect each other
for (int i = 0; i < l.length; i++) {
if (b[i] == 2 && mi == 0) {
div -= l[i];
ab.remove(i);
break;
}
if (b[i] == 1 && t != 2 && mi == 1) {
div -= l[i];
k[t] = i;
t++;
}
if (t == 2) {
ab.remove(k[0]);
ab.remove(k[1] - 1);
break;
}
}
if (div % 3 != 0) {
return 0;
}
}
if (ab.size() >= 1) {//Here we will check whether size of result is more than zero just in case there was only element in the array which might have no more elements now.
int result = 0;
Integer[] res = ab.toArray(new Integer[ab.size()]);
for (int i = res.length - 1; i >= 0; i--) {
result = 10 * result + res[i];
}
return result;
}
else {
return 0;
}
}
public static void main(String[] arg)
{
int a[]={7,7,7,6};
Main d=new Main();
int f=d.answer(a);
System.out.print(f);
}
爲什麼不修改它來打印輸入,以便在測試用例失敗時可以看到輸入是什麼?然後,使用您的調試器來了解該特定輸入會發生什麼。 –
您的問題描述很模糊,程序非常難以理解。我最終放棄了試圖理解它的作用。 – Henry
爲什麼不能對給定的數字進行排序,然後搜索它? – sForSujit