Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up: Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
intDiv(unsigned a,unsigned b){ int x,y; int ans = 0; while(a >= b) { x = b; y = 1; while( a >= (x<<1)) { x <<= 1; y <<= 1; } a -= x; ans += y; } return ans; } intdiv(int a,int b){ if (a > 0 && b > 0) return Div(a,b); elseif (a < 0 && b < 0) return Div(-a,-b); elseif (a < 0) return -Div(-a,b); elsereturn -Div(a,-b); }
defproductExceptSelf(self, nums): p = 1 n = len(nums) output = [] for i inrange(0,n): output.append(p) p = p * nums[i] p = 1 for i inrange(n-1,-1,-1): output[i] = output[i] * p p = p * nums[i] return output