Ques: Given an array of ints, return true if every 2 that appears in the array is next to another 2.
Ans:
public boolean twoTwo(int[] nums) {
boolean count=true;
//Check if there is one element and that is 2 then set the count flag to false
if(nums.length==1){if(nums[0]==2)count=false;}
//if the number of elements are greater than 1
for(int i=1;i<nums.length;i++){
if(nums[i]==2&&nums.length>1){
//check wehther the next element is 2?
if(nums[i-1]==2){
count=true;
i++;
}else{ count=false;}
}
}
return count;
}
Ans:
public boolean twoTwo(int[] nums) {
boolean count=true;
//Check if there is one element and that is 2 then set the count flag to false
if(nums.length==1){if(nums[0]==2)count=false;}
//if the number of elements are greater than 1
for(int i=1;i<nums.length;i++){
if(nums[i]==2&&nums.length>1){
//check wehther the next element is 2?
if(nums[i-1]==2){
count=true;
i++;
}else{ count=false;}
}
}
return count;
}
No comments:
Post a Comment