Java > Array-1 > has23 (CodingBat Solution)

Problem:

Given an int array length 2, return true if it contains a 2 or a 3.

has23({2, 5}) → true
has23({4, 3}) → true
has23({4, 5}) → false


Solution:

public boolean has23(int[] nums) {
  if (nums[0] == 2 || nums[0] == 3 || nums[1] == 2 || nums[1] == 3)
    return true;
  else
    return false;
}


10 comments :

  1. You can shorten this to:
    return (nums[0] == 2 || nums[0] == 3 || nums[1] == 2 || nums[1] == 3);

    ReplyDelete
    Replies
    1. uR SO smaRT i wANTeD 2 SSSSAYAYAYA dat

      Delete
  2. public boolean has23(int[] nums) {
    if(nums[0] == 2 || nums[0] == 3 || nums[1] == 2 || nums [1] == 3)
    {
    return true;
    }
    else
    {
    return false;
    }
    }

    ReplyDelete
  3. String str = String.valueOf(nums[0]) + String.valueOf(nums[1]);
    return(str.contains("2")||str.contains("3"));
    //More easy way

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

    ReplyDelete
  5. public boolean has23(int[] nums) {
    for(int x : nums){
    if(x == 2 || x == 3){
    return true;
    }
    }
    return false;
    }

    ReplyDelete
  6. boolean isContians = false;
    for(int i = 0; i<nums.length; i++){
    if(nums[0]==2 || nums[0] == 3 || nums[1]==2 || nums[1] == 3) {
    isContians = true;
    }else{
    isContians = false;
    }

    }
    return isContians;

    ReplyDelete
  7. public boolean has23(int[] nums) {
    boolean isTwoThree = false;
    for(int each:nums){
    if(each==2 || each==3){
    isTwoThree = true;
    }

    }
    return isTwoThree;
    }

    ReplyDelete
  8. basic logic

    public boolean has23(int[] nums) {
    if(nums[0]==2||nums[0]==3){
    return true;
    }
    else
    if(nums[1]==2||nums[1]==3){
    return true;
    }
    else {
    return false;
    }
    }

    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