3 回答

TA貢獻1773條經驗 獲得超3個贊
試試這個,我測試了它并且它有效,你應該使用余數運算符%:
public class Array {
public static void main(String[] args) {
int[] arr = {2, 3, 5, 7, 11};
System.out.println(is235Array(arr));
}
public static int is235Array(int[] a) {
int countOne = 0;
int countTwo = 0;
for (int i : a) {
if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0) {
countOne++;
}else{countTwo++;}
}
if (countOne + countTwo != a.length) {
return 0;
}else{return 1;}
}
}

TA貢獻1906條經驗 獲得超10個贊
檢查數組是否為 235。is235Array。
public class Array{
static int is235Array(int[] a){
int countNonMultiples = 0;
int countMultiplesOfTwo = 0;
int countMultiplesOfThree = 0;
int countMultiplesOfFive = 0;
for (int i : a){
if(i % 2 == 0 ){
countMultiplesOfTwo++;
}
if(i % 3 == 0){
countMultiplesOfThree++;
}
if(i % 5 == 0){
countMultiplesOfFive++;
}
if(i % 2 != 0 && i % 3 != 0 && i % 5 != 0 ){
countNonMultiples++;
}
}
if(countMultiplesOfTwo + countMultiplesOfThree + countMultiplesOfFive + countNonMultiples != a.length){
return 0;
}
return 1;
}
public static void main(String[] args) {
int[] arr = {7,2,7,2,7,2,7,2,3,7,7};
System.out.println(is235Array(arr));
}
}

TA貢獻1936條經驗 獲得超7個贊
當你想比較一個整數是否可以被一個數字整除時,你應該使用余數運算符
所以這是代碼:
public class Array {
? ? public static void main(String[] args) {
? ? ? ? int[] arr = {2, 3, 5, 7, 11};
? ? ? ? System.out.println(is235Array(arr));
? ? }
? ? public static int is235Array(int[] a) {
? ? ? ? int n = a.length;
? ? ? ? int countOne = 0;
? ? ? ? int countTwo = 0;
? ? ? ? for (int i = 0; i < a.length; i++) {
? ? ? ? ? ? if (a[i] % 2 == 0 || a[i] % 3 == 0 || a[i] / 5 == 0) {
? ? ? ? ? ? ? ? countOne++;
? ? ? ? ? ? }else{countTwo++;}
? ? ? ? }
? ? ? ? if (countOne + countTwo != n) {
? ? ? ? ? ? return 0;
? ? ? ? }else{return 1;}
? ? }
}
另請注意,沒有必要編寫 2nd,for loop因為它根本沒有必要,而且如果您可以使用單個 for 循環完成任務,這是一種不好的做法。
另外如上所述,問題的答案for-each loop是, a比常規方法[性能方面]更好for loop,因此使用 afor-each loop會變成:
public class Array {
? ? public static void main(String[] args) {
? ? ? ? int[] arr = {2, 3, 5, 7, 11};
? ? ? ? System.out.println(is235Array(arr));
? ? }
? ? public static int is235Array(int[] a) {
? ? ? ? int countOne = 0;
? ? ? ? int countTwo = 0;
? ? ? ? for (int i : a) {
? ? ? ? ? ? if (i % 2 == 0 || i % 3 == 0 || i / 5 == 0) {
? ? ? ? ? ? ? ? countOne++;
? ? ? ? ? ? }else{countTwo++;}
? ? ? ? }
? ? ? ? if (countOne + countTwo != a.length) {
? ? ? ? ? ? return 0;
? ? ? ? }else{return 1;}
? ? }
}
添加回答
舉報