Problem:
Given an array of ints, return true if the array contains either 3 even or 3 odd values all next to each other.
modThree({2, 1, 3, 5}) → true
modThree({2, 1, 2, 5}) → false
modThree({2, 4, 2, 5}) → true
Solution:
public boolean modThree(int[] nums) { int odd = 0; int even = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] % 2 == 0) { even++; if (odd < 3) odd = 0; } else { odd++; if (even < 3) even = 0; } } return (odd == 3 || even == 3); }
Here's a more general/quicker way:
ReplyDeletepublic boolean modThree(int[] nums) {
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i]%2 == nums[i + 1]%2 && nums[i]%2 == nums[i + 2]%2 ) return true;
}
return false;
}
nice
Deletepublic boolean modThree(int[] nums) {
ReplyDeleteboolean result = false;
for (int i = 1; i<nums.length-1; i++){
if(nums[i-1]%2==0 && nums[i]%2==0 && nums[i+1]%2==0)
result = true;
else if(nums[i-1]%2==1 && nums[i]%2==1 && nums[i+1]%2==1)
result = true;
}return result;
}
function modThree() {
ReplyDeletevar intArray = [0,2, 4, 3, 5];
var modThreeFlag = false;
for (var i = 0; i < intArray.length - 2; i++) {
if (intArray[i] % 2 == 0 && intArray[i + 1] % 2 == 0 && intArray[i + 2] % 2 == 0) {
modThreeFlag = true;
break;
}
else if (intArray[i] % 2 == 1 && intArray[i + 1] % 2 == 1 && intArray[i + 2] % 2 == 1) {
modThreeFlag = true;
break;
}
else {
modThreeFlag = false;
}
}
var intArrayString = intArray.join().toString();
document.getElementById("outputText").value = modThreeFlag;
}
public boolean modThree(int[] nums) {
ReplyDeleteboolean one = false;
boolean two = false;
for(int i =0; i < nums.length-2; i++){
if(nums[i]%2==0){
if(nums[i+1]%2==0){
if(nums[i+2]%2==0){
one = true;
}
}
}
}
for(int i = 0; i < nums.length-2; i++){
if(nums[i]%2!=0){
if(nums[i+1]%2!=0){
if(nums[i+2]%2!=0){
two = true;
}
}
}
}
return (one||two);
}
public boolean modThree(int[] nums) {
ReplyDeleteint even=0;
int odd =0;
boolean flag = false;
for(int i=0 ; i<nums.length ;i++){
if(nums[i]%2==0) {
even++;
if(even==3)
{
flag = true ;
break;
}
}
else {
even=0;
}
if(nums[i]%2!=0) {
odd++;
if(odd==3)
{
flag = true ;
break;
}
}
else {
odd=0;
}
}
return flag;
}