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条经验 获得超6个赞
当你想比较一个整数是否可以被一个数字整除时,你应该使用余数运算符
所以这是代码:
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;}
}
}
添加回答
举报