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; }
public int[] fix23(int[] nums) {
ReplyDeleteif (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;}
}
public int[] fix23(int[] nums) {
ReplyDeleteif (nums[0] == 2 && nums[1] == 3) {
nums[1] = 0;
}
if (nums[1] == 2 && nums[2] == 3) {
nums[2] = 0;
}
return nums;
}
public int[] fix23(int[] nums) {
ReplyDeletefor (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;
}
Solve without loops
Deletepublic int[] fix23(int[] nums) {
ReplyDeleteif(nums[0] == 2 && nums[1] == 3){
nums[1] = 0;
}else if(nums[1] == 2 && nums[2] == 3){
nums[2] = 0;
}
return nums;
}
public int[] fix23(int[] nums) {
ReplyDeleteif(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;
}
}