Hello,
I've been studying some questions in preparation for an interview. One of them has given me some trouble.
Since it's an interview prep question, I don't want anyone to just give me the answer.
I believe I might be headed in the right direction; I would just like to know if I am anywhere in the ballpark, and how to go about implementing this if I am.
This is the question:
5. Consider the following code:
int CheckForZero (int a[], int n)
{
int i;
for (i = 0; i < n; i++) {
if (a[i] == 0) {
return (TRUE);
}
}
return (FALSE);
}
This code works - but it does a check for every element in 'a' - i.e.
it does "n" compares and bails early if it finds even one zero element.
Our array 'a' generally does not have a zero. Optimize this code to
do only one compare. Feel free to instead use some mathematical
operations such as ADD, SUB etc.
What I think might be the solution is to create another array of the same length that is completely composed of 1s.
Then, use this array as a sort of mask. Is there some way to multiply or to AND entire arrays in a single fell swoop?
Thanks in advance,
Tim
Start Free Trial