英文:
I have to figure out if the numbers in an array are factors of a given number
问题
public static boolean areFactors(int[] arrNum, int n){
if (arrNum == null || arrNum.length == 0){
return false;
}
for (int i = 0; i < arrNum.length; i++){
if (n % arrNum[i] == 0){
return true;
}
}
return false;
}
英文:
Ex:
- areFactors( [3,4,6], 12 ) --> true
- areFactors( [2,4,6], 10 ) --> false
- areFactors( [], 6 ) --> false
public static boolean areFactors(int[] arrNum, int n){
if (arrNum == null || arrNum.length == 0){
return false;
}
for (int i = 0; i < arrNum.length; i++){
if (n % arrNum[i] == 0){
return true;
}
}
return false;
}
There are a few tests that won't pass and I also get division by zero exception.
答案1
得分: 2
如果数组中包含任何0,则应返回false。
除此之外,在遇到不是n
的因子的数字时,应返回false
。
仅在循环之后返回true
(即在验证所有数组元素都是n
的因子后返回)。
public static boolean areFactors(int[] arrNum, int n) {
if (arrNum == null || arrNum.length == 0) {
return false;
}
for (int i = 0; i < arrNum.length; i++) {
if (arrNum[i] == 0 || n % arrNum[i] != 0) {
return false;
}
}
return true;
}
英文:
If the array contains any 0s, you should return false.
Other than that, you should return false
when you encounter a number that is not a factor of n
.
Return true
only after the loop (i.e. after validating that all the array elements are factors of n
).
public static boolean areFactors (int[] arrNum, int n) {
if (arrNum == null || arrNum.length == 0) {
return false;
}
for (int i = 0; i < arrNum.length; i++) {
if (arrNum[i] == 0 || n % arrNum[i] != 0) {
return false;
}
}
return true;
}
答案2
得分: 0
你的代码中存在一个逻辑错误。
在这里,你可以找到一个解决方案,以实现你想要的功能:
public static boolean areFactors(int[] arrNum, int n) {
if (arrNum == null || arrNum.length == 0) {
return false;
}
for (int i = 0; i < arrNum.length; i++) {
int num = arrNum[i];
if (num != 0 && n % num != 0) {
return false;
}
}
return true;
}
英文:
There is a logical error in your code.
Here you can find a solution what you are going to achieve:
public static boolean areFactors(int[] arrNum, int n) {
if (arrNum == null || arrNum.length == 0) {
return false;
}
for (int i = 0; i < arrNum.length; i++) {
int num = arrNum[i];
if (num != 0 && n % num != 0) {
return false;
}
}
return true;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论