Wednesday, April 20, 2016

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

Given an array of ints, return true if the array contains two 7's next to each other, or there are two 7's separated by one element, such as with {7, 1, 7}.

has77([1, 7, 7]) → true
has77([1, 7, 1, 7]) → true
has77([1, 7, 1, 1, 7]) → false

Answer 1:

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

Answer 2:

public boolean has77(int[] nums) {
boolean result = false;

  for (int i = 0; i < nums.length-1; i++)
  if ((nums[i] == 7 && nums[i+1] == 7))
  result = true;
 
   for (int i = 0; i < nums.length-2; i++)
  if ((nums[i] == 7 && nums[i+2] == 7))
  result = true;

Reference

http://www.javaproblems.com/2012/12/coding-bat-java-array-2-has77.html

No comments :

Post a Comment