From 5a3a8d32a4ad3408592599225cd5c836717e32eb Mon Sep 17 00:00:00 2001 From: Eatswap Date: Thu, 27 Oct 2022 13:47:01 +0800 Subject: [PATCH] add: 221027-CN --- cpp/2210/221027-CN.cpp | 36 ++++++++++++++++++++++++++++++++++++ cpp/2210/CMakeLists.txt | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 cpp/2210/221027-CN.cpp diff --git a/cpp/2210/221027-CN.cpp b/cpp/2210/221027-CN.cpp new file mode 100644 index 0000000..2e9c2fe --- /dev/null +++ b/cpp/2210/221027-CN.cpp @@ -0,0 +1,36 @@ +#include + +/** + * 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& 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; + } +}; diff --git a/cpp/2210/CMakeLists.txt b/cpp/2210/CMakeLists.txt index da71f7a..2bc0125 100644 --- a/cpp/2210/CMakeLists.txt +++ b/cpp/2210/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2210) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2210 221026.cpp) +ADD_EXECUTABLE(2210 221027-CN.cpp)