Problem:
Given an array of ints, return true if the array contains no 1's and no 3's.
lucky13({0, 2, 4}) → true
lucky13({1, 2, 3}) → false
lucky13({1, 2, 4}) → false
Solution:
public boolean lucky13(int[] nums) { boolean no13 = true; for (int i = 0; i < nums.length; i++) { if (nums[i] == 1 || nums[i] == 3) no13 = false; } return no13; }
A shorter version:
ReplyDeletepublic boolean lucky13(int[] nums) {
for (int n : nums) {
if (n == 1 || n == 3) return false;
}
return true;
}
public boolean lucky13(int[] nums) {
ReplyDeleteboolean results = true;
for(int i = 0; i<nums.length; i++)
for(int k = 0; k<nums.length; k++)
{
if((nums[i] == 1) || (nums[k] == 3))
results = false;
}
return results;
}
public boolean lucky13(int[] nums) {
ReplyDeleteboolean counter = true;
for(int i=0; i<nums.length;i++)
if(nums[i]==1 || nums[i]==3)
counter = false;
return counter;
}
Using Java Stream
ReplyDeletepublic static boolean lucky13(int[] nums) {
List list = Arrays.stream(nums).boxed().collect(Collectors.toList());
return !list.contains(1) && !list.contains(3);
}