给定一个包含N 个元素的数组arr[] ,任务是找到给定的操作是否可以使给定数组的所有元素都为 0。在这个数组上只能执行两种类型的操作:
- 将元素 B 拆分为 2 个元素 C 和 D,使得B = C + D 。
- 将 2 个元素 P 和 Q 合并为一个元素 R,使得R = P^Q即(P 和 Q 的异或)。
例子:
Input: arr = [9, 17]
Output: Yes
Explanation: Following is one possible sequence of operations –
1) Merge i.e 9 XOR 17 = 24
2) Split 24 into two parts each of size 12
3) Merge i.e 12 XOR 12 = 0
As there is only 1 element i.e 0. So it is possible.
Input: arr = [1]
Output: No
Explanation: There is no possible way to make it 0.
方法 :
- 如果数组中的任何元素是偶数,则可以将其设为 0。将该元素拆分为 arr[i]/2 和 arr[i]/2 的两个相等部分。两个相等数的异或为零。因此,该策略使元素为 0。
- 如果任何元素是奇数。将其分为两部分:1 和 arr[i]-1。由于 arr[i]-1 是偶数,因此可以通过上述策略使其为 0。因此,奇数元素可以将其大小减少到 1。因此,可以通过遵循上述策略使两个奇数元素为 0,最后将它们(即 1)异或(即 1)为 1 XOR 1 = 0。因此,如果数组中的奇数元素数是偶数,那么答案是可能的。否则,将留下值为 1 的元素,无法满足条件。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function that finds if it is
// possible to make the array
// contain only 1 element i.e. 0
string solve(vector& A)
{
int i, ctr = 0;
for (i = 0; i < A.size();
i++) {
// Check if element is odd
if (A[i] % 2) {
ctr++;
}
}
// According to the logic
// in above approach
if (ctr % 2) {
return "No";
}
else {
return "Yes";
}
}
// Driver code
int main()
{
vector arr = { 9, 17 };
cout << solve(arr) << endl;
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function that finds if it is
// possible to make the array
// contain only 1 element i.e. 0
public static String solve(int[] A)
{
int i, ctr = 0;
for(i = 0; i < A.length; i++)
{
// Check if element is odd
if (A[i] % 2 == 1)
{
ctr++;
}
}
// According to the logic
// in above approach
if (ctr % 2 == 1)
{
return "No";
}
else
{
return "Yes";
}
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 9, 17 };
System.out.println(solve(arr));
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program for the above approach
# Function that finds if it is
# possible to make the array
# contain only 1 element i.e. 0
def solve(A):
ctr = 0
for i in range(len(A)):
# Check if element is odd
if A[i] % 2 == 1:
ctr += 1
# According to the logic
# in above approach
if ctr % 2 == 1:
return 'No'
else :
return 'Yes'
# Driver code
if __name__=='__main__':
arr = [9, 17]
print(solve(arr))
# This code is contributed by rutvik_56
C#
// C# program for the above approach
using System;
class GFG{
// Function that finds if it is
// possible to make the array
// contain only 1 element i.e. 0
public static string solve(int[] A)
{
int i, ctr = 0;
for(i = 0; i < A.Length; i++)
{
// Check if element is odd
if (A[i] % 2 == 1)
{
ctr++;
}
}
// According to the logic
// in above approach
if (ctr % 2 == 1)
{
return "No";
}
else
{
return "Yes";
}
}
// Driver code
public static void Main()
{
int[] arr = { 9, 17 };
Console.Write(solve(arr));
}
}
// This code is contributed by chitranayal
Javascript
输出:
Yes
时间复杂度: O(N)
辅助空间复杂度: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live