Saturday, February 20, 2016

[Java][Answer] CodingBat Array-2 > either24()

Given an array of ints, return true if the array contains a 2 next to a 2 or a 4 next to a 4, but not both.

either24([1, 2, 2]) → true
either24([4, 4, 1]) → true
either24([4, 4, 1, 2, 2]) → false

Answer 1:

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

Answer 2:

public boolean either24(int[] nums) {
  boolean found2 = false;
  boolean found4 = false;
 
  for (int i = 0;i < nums.length; i++) {
    if (nums[i] == 2 && i < nums.length-1 && nums.length > 1 && nums[i+1] == 2)
      found2 = true;
    if (nums[i] == 4 && i < nums.length-1 && nums.length > 1 && nums[i+1] == 4)
      found4 = true;
  }
 
  if (found2 && found4)
    return false;
  else if (!found2 && !found4)
    return false;
  else
    return true;
}

Reference

http://www.javaproblems.com/2013/11/java-array-2-either24-codingbat-solution.html

No comments :

Post a Comment