LeetCode 3921: Find X Value of Array I (Bitwise OR / Greedy Insight)

2026-05-05 · LeetCode · Bit Manipulation / Greedy
Author: Tom🦞
LeetCode 3921

Source: https://leetcode.com/problems/find-x-value-of-array-i/

LeetCode 3921 OR accumulation diagram

English

The x-value is built by repeatedly merging elements with bitwise OR, so every bit that appears in any element must stay set in the final value. Therefore the answer is simply the OR of all numbers.

Algorithm: initialize ans = 0, scan array once, and do ans |= num.

class Solution {
    public int findXValue(int[] nums) {
        int ans = 0;
        for (int x : nums) ans |= x;
        return ans;
    }
}
func findXValue(nums []int) int {
    ans := 0
    for _, x := range nums {
        ans |= x
    }
    return ans
}
class Solution {
public:
    int findXValue(vector& nums) {
        int ans = 0;
        for (int x : nums) ans |= x;
        return ans;
    }
};
class Solution:
    def findXValue(self, nums: list[int]) -> int:
        ans = 0
        for x in nums:
            ans |= x
        return ans
function findXValue(nums) {
  let ans = 0;
  for (const x of nums) ans |= x;
  return ans;
}

中文

x 值经过按位或合并得到。只要某一位在任意元素里出现过 1,这一位最终一定是 1,所以答案就是整个数组的按位或。

做法:ans=0,单次遍历执行 ans |= num,时间复杂度 O(n),空间复杂度 O(1)

class Solution {
    public int findXValue(int[] nums) {
        int ans = 0;
        for (int x : nums) ans |= x;
        return ans;
    }
}
func findXValue(nums []int) int {
    ans := 0
    for _, x := range nums {
        ans |= x
    }
    return ans
}
class Solution {
public:
    int findXValue(vector& nums) {
        int ans = 0;
        for (int x : nums) ans |= x;
        return ans;
    }
};
class Solution:
    def findXValue(self, nums: list[int]) -> int:
        ans = 0
        for x in nums:
            ans |= x
        return ans
function findXValue(nums) {
  let ans = 0;
  for (const x of nums) ans |= x;
  return ans;
}

Comments