[英]Empty array returns true? Given an array of ints, return true if every element is a 1 or a 4
Given an array of ints, return true if every element is a 1 or a 4. only14([1, 4, 1, 4]) → true only14([1, 4, 2, 4]) → false only14([1, 1]) → true
I came up with the following algorithm which returns all the expected answers, EXCEPT for an empty array which should return true
:我想出了以下算法,它返回所有预期的答案,除了一个应该返回
true
的空数组:
public boolean only14(int[] nums) {
boolean flag = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1 || nums[i] == 4) {
flag = true;
} else {
return false;
}
}
return flag;
}
From the solutions, the following input should yield true
, but I can't figure out why:从解决方案中,以下输入应该产生
true
,但我不知道为什么:
only14([]) → true
I understand the default value is 0, so what am I missing such that I should expect the return value of the boolean to be true
?我知道默认值是 0,所以我错过了什么,以至于我应该期望布尔值的返回值为
true
?
The following should work.以下应该工作。 It returns
true
unless there are any values that are not 1 or 4.除非有任何不是 1 或 4 的值,否则它会返回
true
。
public boolean only14(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int val = nums[i];
if (val != 1 && val != 4) {
return false;
}
}
return true;
}
The empty set contains no values that aren't 1
or 4
, so it should be true
.空集不包含不是
1
或4
,所以它应该是true
。 I would prefer a for-each
loop like我更喜欢
for-each
循环
public boolean only14(int[] nums) {
for (int n : nums) { // for each int n in nums
if (n == 1 || n == 4) { // if it is 1 or 4 keep looping
continue;
}
return false; // it isn't 1 or 4, return false
}
return true; // every value is 1 or 4.
}
In Java 8+, you could implement it with an IntStream
like在 Java 8+ 中,您可以使用
IntStream
来实现它,例如
public boolean only14(int[] nums) {
return IntStream.of(nums).allMatch(x -> x == 1 || x == 4);
}
This code works fine:-此代码工作正常:-
public boolean only14(int[] nums) {
for(int i=0;i<=nums.length-1;i++){
if (nums[i]!= 1 && nums[i]!= 4){
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.