samedi 27 juin 2020

Return true if the array contains either 3 even or 3 odd values all next to each other

While I was practicing Java Problems on coding bat I came across the following problem statement:-

Problem:-

Given an array of integers, return true if the array contains either 3 even or 3 odd values all next to each other.

Example:-

modThree([2, 1, 3, 5]) → true
modThree([2, 1, 2, 5]) → false
modThree([2, 4, 2, 5]) → true

My Solution:-

public boolean modThree(int[] nums) {
  for(int i=0;i<nums.length-2;i++){
    if((nums[i]%2==0&&nums[i+1]%2==0&&nums[i+2]%2==0)||(nums[i]%2==1 && nums[i+1]%2==1 && nums[i+2]%2==1)){
      return true;
    }
  }
    return false;
}

Though my solution works, my solution looks a bit long(especially the if statement condition). So, I am looking for a solution with fewer lines of code. Can you help me with this?

Aucun commentaire:

Enregistrer un commentaire