-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProductExceptSelf.cpp
60 lines (53 loc) · 1.14 KB
/
ProductExceptSelf.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
*
* Title: Product of Array Except Self
* Description: Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
* Author: Ajit Panigrahi
* GitHub: https://github.com/AjitZero
* Twitter: https://twitter.com/AjitZero
*
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* Calculates the product of all elements except the one in position
*
* @param nums [list of integers]
*/
void productExceptSelf(vector<int>& nums) {
int N = nums.size();
vector<int> results(N, 1);
for (int i = 0; i < N; ++i) {
results[i] = nums[i - 1] * results[i - 1];
}
int t = 1;
for (int i = N - 1; i >= 0; --i) {
results[i] *= t;
t *= nums[i];
}
for (auto &elem: results) {
cout << elem << ' ';
}
cout << endl;
}
// Driver function
int main() {
int n;
cin >> n;
vector<int> input(n);
for (int i = 0; i < n; ++i) {
cin >> input[i];
}
productExceptSelf(input);
return 0;
}
/*
Sample Input:
--------------------
4
1 2 3 4
Sample Output:
--------------------
24 12 8 6
*/