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;
    return nums;
  }
  if (nums[1] == 2 && nums[2] == 3) {
    nums[2] = 0;
    return nums;
  } else
    return nums;
}


6 comments :

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

    ReplyDelete
  2. 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 nums;
    }

    ReplyDelete
  3. public int[] fix23(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
    if (i == nums.length - 1) {
    break;
    } else if (nums[i] == 2 && nums[i + 1] == 3) {
    nums[i + 1] = 0;
    return nums;
    }
    }
    return nums;
    }

    ReplyDelete
  4. 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
  5. public int[] fix23(int[] nums) {
    if(nums[0]==2&&nums[1]==3){
    int[] arr=new int[]{nums[0],0,nums[2]};
    return arr;

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

    }
    else
    {
    int[] c=new int[]{nums[0], nums[1], nums[2]};
    return c;
    }
    }

    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