Friday, December 20, 2013

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

Given an array of ints, return true if it contains no 1's or it contains no 4's.

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

Answer 1:

public boolean no14(int[] nums) {
  int count1 = 0;
  int count4 = 0;
  for(int i =0;i<nums.length;i++){
    if(nums[i]==1) count1++;
    if(nums[i]==4) count4++;
  }
  return count1==0 ||count4==0 ;
}

Answer 2:

public boolean no14(int[] nums) {
boolean two = false,four = false;
for(int count = 0;count <nums.length; count++) {
if (nums[count] == 1)
two = true;
if(nums[count] == 4)
four = true;
 }
if(nums.length == 0 || nums.length == 1)
return true;
else if (two ==true && four ==true)
 return false;
else if (two || four)
return true;
else
return false; }

Reference

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

No comments :

Post a Comment