Saturday, April 20, 2013

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

Given an array of ints, return true if the number of 1's is greater than the number of 4's

more14([1, 4, 1]) → true
more14([1, 4, 1, 4]) → false
more14([1, 1]) → true

Answer 1:
public boolean more14(int[] nums) {
  int count1 = 0;
  int count4 = 0;
  for(int i=0;i<nums.length;i++){
    if(nums[i]==1) count1++;
    else if(nums[i]==4) count4++;
  }
  return count1>count4;
}


Answer 2:
public boolean more14(int[] nums) {
  int count1 = 0;
  int count4 = 0;
  boolean isTrue = false;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 1)
      count1++;
    if (nums[i] == 4)
      count4++;
  }
 
  if (count1 > count4)
    isTrue = true;
 
  return isTrue;
   
}

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

No comments :

Post a Comment