Kevin Zheng Kevin Zheng - 7 months ago 54
Java Question

Codingbat array2 no14

i am doing problems in codingbat. About this problem, i think i have done correctly but the result is not right. Plz help me find out the mistakes.The problem is:Given an array of ints, return true if it contains no 1's or it contains no 4's.

no14({1, 2, 3}) → true
no14({1, 2, 3, 4}) → false
no14({2, 3, 4}) → true


the following are my codes:

public boolean no14(int[] nums) {
int i=0;
int count1=0;
int count4=0;
while(i<nums.length)
{
if(nums[i]==1)
{count1++;}
i++;
}
while(i<nums.length)
{
if(nums[i]==4)
{count4++;}
i++;
}
if(count1==0&&count4!=0)
{return true;}
else if(count1!=0&&count4==0)
{return true;}
else if(count1==0&&count4==0)
{return true;}
else return false;
}

Answer

After the first while loop, you have to make the value of i to 0 before the second while

 while(i<nums.length)
   {
   if(nums[i]==1)
    {count1++;}
    i++;
   }
    i = 0;
   while(i<nums.length)
   {
     if(nums[i]==4)
     {count4++;}
     i++;
   }

You can return false as soon as you find a 1 or 4 to make it efficient.

Comments