Java > Array-1 > double23 (CodingBat Solution)

Problem:

Given an int array, return true if the array contains 2 twice, or 3 twice. The array will be length 0, 1, or 2.

double23({2, 2}) → true
double23({3, 3}) → true
double23({2, 3}) → false


Solution:

public boolean double23(int[] nums) {
  if (nums.length < 2)
    return false;
  if ((nums[0] == 2 && nums[1] == 2) || (nums[0] == 3 && nums[1] == 3))
    return true;
  else
    return false;
}


6 comments :

  1. public boolean double23(int[] nums) {
    return (nums.length==2 && ((nums[0]==2 && nums[1]==2) || (nums[0]==3 && nums[1]==3)));
    }

    ReplyDelete
  2. public boolean double23(int[]nums){
    return (nums.length>1&&nums[0]==nums[1])&&(nums[0]==2||nums[0]==3);
    }

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

    if (nums.length < 2)
    return false;

    if (nums[0] == 2 && nums[1] == 2 || nums[0] == 3 && nums[1] == 3)
    return true;
    else
    return false;

    }

    ReplyDelete
  4. public boolean double23(int[] nums) {
    int count2=0;
    int count3=0;
    if(nums.length<2){
    return false;
    }else{
    for(int i=0;i<nums.length;i++){
    if(nums[i]==2){
    count2++;
    }
    if(nums[i]==3){
    count3++;
    }

    }
    if(count2==2 || count3==2){
    return true;
    }

    }
    return false;
    }

    ReplyDelete
  5. public boolean double23(int[] nums) {
    int c2 = 0;
    int c3 = 0;
    for (int each : nums)
    if (each == 2){
    c2++;
    }else if(each ==3){
    c3++;
    }
    return c2 == 2 || c3 == 2;

    ReplyDelete
  6. public boolean double23(int[] nums) {
    if(nums.length<2)
    return false;
    if(nums[0]==nums[nums.length-1]){
    return true;
    }

    return false;
    }


    is that right

    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