Sunday, November 20, 2016

[Java][Answer] CodingBat Array-2 > lucky13

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

Answer 1:

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

Answer 2:

public boolean lucky13(int[] nums) {
  boolean no1 = true;
  boolean no3 = true;
  for(int i=0;i<nums.length;i++){
    if(nums[i]==1) no1=false;
    if(nums[i]==3) no3=false;
  }
  return no1 && no3;
}

Reference

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

No comments :

Post a Comment