Handling ' 0 's
Case1: array containing single zero.
Caae 2: array containing multiple zeros.


int numberofZeros =0, index =0 ;
before[0]=1
after[length-1]=1;

for (int i=1; i<length;i++)
{

  if( !a[i] ) //encountered zero
  {
    numberofZeros++;
    if(numberofZeros == 1) index =i; //Case1 handling
    before[i] = before[i-1];
    after[length-1-i] = after[length-i];
  }
  else if (numberofZeros<=1)
  {
    before[i]=a[i]*before[i-1];
    after[length-1-i]=a[length-1-i]*after[length-i];
  }
  else break; //Case2 handling
}

for(int i=0;i<length; i++) // replace array contents as per the question.
{
    if(numberofZeros == 1)
    {
      if(i ==index)
           a[index] = before[index] * after[index];
       else
           a[i] = 0;
    }
    else if(numberofZeros>1)
    {
     a[i]=0;
    }
    else
    {
      a[i] = before[i] * after[i];
    }
}

Thanks,
NagRaaj.

On Sun, Sep 19, 2010 at 8:24 PM, Ashish Goel <ashg...@gmail.com> wrote:

> this is google question
>
> take arrays before[] and after
>
> before[0]=1
> after[length-1]=1;
>
> for (int i=1; i<length;i++)
> {
>  before[i]=a[i]*before[i-1];
>  after[length-1-i]=a[length-1-i]*after[length-i];
> }
>
> now resuly for the asked index is after[index]*before[index]
>
>
> the idea here is that we should not be using division..
>
>
> additionally, you can improve it if any of the numbers is zero
>
>
>
>
>
>
> Best Regards
> Ashish Goel
> "Think positive and find fuel in failure"
> +919985813081
> +919966006652
>
>
> On Sun, Sep 19, 2010 at 8:18 PM, bittu <shashank7andr...@gmail.com> wrote:
>
>>
>> Given an array of numbers, replace each number with the product of
>> all the numbers in the array except the number itself *without* using
>> division.
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Algorithm Geeks" group.
>> To post to this group, send email to algoge...@googlegroups.com.
>> To unsubscribe from this group, send email to
>> algogeeks+unsubscr...@googlegroups.com<algogeeks%2bunsubscr...@googlegroups.com>
>> .
>> For more options, visit this group at
>> http://groups.google.com/group/algogeeks?hl=en.
>>
>>
>  --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To post to this group, send email to algoge...@googlegroups.com.
> To unsubscribe from this group, send email to
> algogeeks+unsubscr...@googlegroups.com<algogeeks%2bunsubscr...@googlegroups.com>
> .
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algoge...@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to