Java > Array-2 > lucky13 (CodingBat Solution)

Problem:

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


Solution:

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


4 comments :

  1. A shorter version:

    public boolean lucky13(int[] nums) {
    for (int n : nums) {
    if (n == 1 || n == 3) return false;
    }
    return true;
    }

    ReplyDelete
  2. public boolean lucky13(int[] nums) {
    boolean results = true;
    for(int i = 0; i<nums.length; i++)
    for(int k = 0; k<nums.length; k++)
    {
    if((nums[i] == 1) || (nums[k] == 3))
    results = false;
    }
    return results;
    }

    ReplyDelete
  3. public boolean lucky13(int[] nums) {

    boolean counter = true;

    for(int i=0; i<nums.length;i++)
    if(nums[i]==1 || nums[i]==3)
    counter = false;
    return counter;

    }

    ReplyDelete
  4. Using Java Stream

    public static boolean lucky13(int[] nums) {

    List list = Arrays.stream(nums).boxed().collect(Collectors.toList());
    return !list.contains(1) && !list.contains(3);
    }

    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