返回介绍

solution / 2600-2699 / 2683.Neighboring Bitwise XOR / README_EN

发布于 2024-06-17 01:03:01 字数 3851 浏览 0 评论 0 收藏 0

2683. Neighboring Bitwise XOR

中文文档

Description

A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original of length n.

Specifically, for each index i in the range [0, n - 1]:

  • If i = n - 1, then derived[i] = original[i] ⊕ original[0].
  • Otherwise, derived[i] = original[i] ⊕ original[i + 1].

Given an array derived, your task is to determine whether there exists a valid binary array original that could have formed derived.

Return _true if such an array exists or false otherwise._

  • A binary array is an array containing only 0's and 1's

 

Example 1:

Input: derived = [1,1,0]
Output: true
Explanation: A valid original array that gives derived is [0,1,0].
derived[0] = original[0] ⊕ original[1] = 0 ⊕ 1 = 1 
derived[1] = original[1] ⊕ original[2] = 1 ⊕ 0 = 1
derived[2] = original[2] ⊕ original[0] = 0 ⊕ 0 = 0

Example 2:

Input: derived = [1,1]
Output: true
Explanation: A valid original array that gives derived is [0,1].
derived[0] = original[0] ⊕ original[1] = 1
derived[1] = original[1] ⊕ original[0] = 1

Example 3:

Input: derived = [1,0]
Output: false
Explanation: There is no valid original array that gives derived.

 

Constraints:

  • n == derived.length
  • 1 <= n <= 105
  • The values in derived are either 0's or 1's

Solutions

Solution 1

class Solution:
  def doesValidArrayExist(self, derived: List[int]) -> bool:
    return reduce(xor, derived) == 0
class Solution {
  public boolean doesValidArrayExist(int[] derived) {
    int s = 0;
    for (int x : derived) {
      s ^= x;
    }
    return s == 0;
  }
}
class Solution {
public:
  bool doesValidArrayExist(vector<int>& derived) {
    int s = 0;
    for (int x : derived) {
      s ^= x;
    }
    return s == 0;
  }
};
func doesValidArrayExist(derived []int) bool {
  s := 0
  for _, x := range derived {
    s ^= x
  }
  return s == 0
}
function doesValidArrayExist(derived: number[]): boolean {
  let s = 0;
  for (const x of derived) {
    s ^= x;
  }
  return s === 0;
}

Solution 2

function doesValidArrayExist(derived: number[]): boolean {
  return derived.reduce((acc, x) => acc ^ x, 0) === 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文