LeetCode 1822. 数组元素积的符号

已知函数 signFunc(x) 将会根据 x 的正负返回特定值:

如果 x 是正数,返回 1 。
如果 x 是负数,返回 -1 。
如果 x 是等于 0 ,返回 0 。
给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。

返回 signFunc(product) 。

class Solution {
public:
    int arraySign(vector<int>& nums) {
        bool negativeFlag = false;
        for (int i : nums) {
            if (0 == i) {
                return 0;
            } else if (i < 0) {
                negativeFlag = !negativeFlag;
            }
        }

        return negativeFlag ? -1 : 1; 
    }
};
posted @ 2021-04-23 18:32  epiphanyy  阅读(6)  评论(0)    收藏  举报  来源