add: 221027-CN

This commit is contained in:
Eatswap 2022-10-27 13:47:01 +08:00
parent da6a7b2dac
commit 5a3a8d32a4
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 37 additions and 1 deletions

36
cpp/2210/221027-CN.cpp Normal file
View File

@ -0,0 +1,36 @@
#include <vector>
/**
* 1822. Sign of the Product of an Array
*
* There is a function signFunc(x) that returns:
* - 1 if x is positive.
* - -1 if x is negative.
* - 0 if x is equal to 0.
* You are given an integer array nums. Let product be the product of all values in the array nums.
* Return signFunc(product).
*/
class Solution {
private:
static constexpr int sgn(int n) {
return n ? ((n >> 31) | 1) : 0;
}
public:
static int arraySign(const std::vector<int>& nums) {
const int MASK = 0xFFFFFFFE, n = nums.size();
int ans = sgn(nums[0]);
if (!ans)
return 0;
for (int i = 1; i < n; ++i) {
switch (sgn(nums[i])) {
case 0:
return 0;
case -1:
ans ^= MASK;
}
}
return ans;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2210)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2210 221026.cpp)
ADD_EXECUTABLE(2210 221027-CN.cpp)