Java > Array-2 > only14 (CodingBat Solution)

Problem:

Given an array of ints, return true if every element is a 1 or a 4.

only14({1, 4, 1, 4}) → true
only14({1, 4, 2, 4}) → false
only14({1, 1}) → true


Solution:

public boolean only14(int[] nums) {
  boolean isTrue = true;
  
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] != 1 && nums[i] != 4)
      isTrue = false;
  }
  return isTrue;
  
}


7 comments :

  1. public boolean only14(int[] nums) {
    boolean isTrue = true;

    for(int i = 0; i < nums.length; i++)
    {
    if(nums[i] != 1 && nums[i] !=4)
    {
    isTrue = false;
    }
    }
    return isTrue;
    }

    ReplyDelete
  2. public boolean only14(int[] nums) {
    for (int i=0; i<nums.length; i++) {

    if(nums[i] != 4 && nums[i] != 1) {
    return false;
    }
    }

    return true;
    }

    ReplyDelete
  3. public boolean only14(int[] nums) {
    boolean bool = false;
    int amount = 0;

    for(int i = 0; i < nums.length; i++){
    if(nums[i] == 1 || nums[i] == 4) {
    amount++;
    }
    }

    if(amount == nums.length){
    return true;
    } else {
    return false;
    }

    }

    ReplyDelete
  4. public boolean only14(int[] nums) {
    for(final int num: nums){
    if(num != 1 && num != 4){
    return false;
    }
    }
    return true;
    }

    ReplyDelete
  5. public boolean more14(int[] nums) {
    int one = 0;
    int four = 0;

    for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 1) one++;
    if (nums[i] == 4) four++;
    }
    return one > four ? true : false;
    }

    ReplyDelete
  6. for(int i = 0; i < nums.length; i++)
    {
    if(nums[i] != 1 && nums[i] != 4) return false;
    }

    return true;

    ReplyDelete
  7. Array-2 > only14
    public boolean only14(int[] nums) {
    int c = 0;
    for(int i =0; i<nums.length;i++){
    if(nums[i]==1)
    c++;
    else if(nums[i]==4)
    c++;}
    return (c == nums.length);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact