3 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
試試這個(gè),我測(cè)試了它并且它有效,你應(yīng)該使用余數(shù)運(yùn)算符%:
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貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
檢查數(shù)組是否為 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貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
當(dāng)你想比較一個(gè)整數(shù)是否可以被一個(gè)數(shù)字整除時(shí),你應(yīng)該使用余數(shù)運(yùn)算符
所以這是代碼:
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;}
? ? }
}
另請(qǐng)注意,沒(méi)有必要編寫 2nd,for loop因?yàn)樗緵](méi)有必要,而且如果您可以使用單個(gè) for 循環(huán)完成任務(wù),這是一種不好的做法。
另外如上所述,問(wèn)題的答案for-each loop是, a比常規(guī)方法[性能方面]更好for loop,因此使用 afor-each loop會(huì)變成:
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;}
? ? }
}
添加回答
舉報(bào)