http://stackoverflow.com/questions/2680548/given-an-array-of-numbers-return-array-of-products-of-all-other-numbers-no-div
Given an array of numbers, return array of products of all other numbers (no division)
solution:
#include <iostream>
using namespace std;
void fill(int *a,int size)
{
for(int i=0;i<size;i++)
{
a[i] = 1;
}
}
int* createProduct(int* a,int size)
{
int temp = 1;
int* products = new int[size];
fill(products,size);
for(int i=0;i<size;i++)
{
products[i] = temp;
temp *= a[i];
}
temp = 1;
for(int i=size-2;i>=0;i--)
{
temp *= a[i+1];
products[i] *= temp;
}
return products;
}
void disp(int* a,int size)
{
for(int i=0;i<size;i++)
{
cout<<a[i]<<"\t";
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int a[] = {6,7,8,4,5};
int size = sizeof(a)/sizeof(*a);
//cout<<sizeof(*a);
int* res = createProduct(a,size);
disp(res,size);
return 0;
}
No comments:
Post a Comment