Java > Array-1 > fix23 (CodingBat Solution)

Problem:

Given an int array length 3, if there is a 2 in the array immediately followed by a 3, set the 3 element to 0. Return the changed array.

fix23({1, 2, 3}) → {1, 2, 0}
fix23({2, 3, 5}) → {2, 0, 5}
fix23({1, 2, 1}) → {1, 2, 1}


Solution:

public int[] fix23(int[] nums) {
  if (nums[0] == 2 && nums[1] == 3)
   nums[1] = 0;
   if (nums[1] == 2 && nums[2] == 3)
   nums[2] = 0;
   return new int[] {nums[0],nums[1],nums[2]};
}



4 comments :

  1. Well it works, but I think you should just return nums; since problem asks us to return "changed array," right?

    ReplyDelete
  2. public int[] fix23(int[] nums) {
    if(nums[0]==2 && nums[1]==3){
    nums[1]=0;
    }
    else if(nums[1]==2 && nums[2]==3){
    nums[2]=0;
    }
    return nums;
    }

    ReplyDelete
  3. public int[] fix23(int[] nums) {
    int pointer1 = 0;
    for(int pointer2 = 1; pointer2 < nums.length; pointer2++){
    if(nums[pointer1] == 2 && nums[pointer2] == 3){
    nums[pointer2] = 0;
    }
    pointer1++;
    }

    return nums;
    }

    ReplyDelete
  4. public int[] fix23(int[] nums) {

    for(int i=0;i<nums.length-1;i++)
    {
    if(nums[i] == 2 && nums[i+1] == 3)
    {
    nums[i+1] = 0;
    }
    }

    return nums;
    }

    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