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 result = true;
  for (int i =0;i<nums.length ;i++)
  if ( nums[i] == 1 || nums[i] == 3)
  result = false;
  return result;
}


7 comments :

  1. public boolean lucky13(int[] nums) {

    for (int i=0; i<nums.length ;i++){

    if (nums[i]==1 || nums[i]==3 ) return false;

    }

    return true;
    }

    ReplyDelete
  2. public boolean lucky13(int[] nums) {
    return !Arrays.toString(nums).contains("1") && !Arrays.toString(nums).contains("3");
    }

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

    return true;
    }

    ReplyDelete
  4. why can't we do
    if(i!==1 && i!==3) return true;

    ReplyDelete
    Replies
    1. Late response, but for everyone else. It's your "&&" operator. It will consider nums[i] to be true only if nums[i] is 1 and 3 (which is not possible)

      Delete
  5. public boolean lucky13(int[] nums)
    {
    HashMap map = new HashMap();

    for(int i = 0; i < nums.length; i++)
    {
    map.put(nums[i], nums[i]);
    }

    return(!map.containsKey(1) && !map.containsKey(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