给定一个具有N个元素的数组arr [] ,任务是查找给定数组的所有元素是否可以通过给定的操作设为0。在此阵列上只能执行两种类型的操作:
- 将元素B拆分为2个元素C和D,使B = C + D。
- 将2个元素P和Q合并为一个元素R,以使R = P ^ Q即(P和Q的XOR)。
例子:
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的两个相等部分。两个相等数字的XOR为零。因此,此策略将元素设置为0。
- 如果任何元素为奇数。将其分为两部分:1和arr [i] -1。由于arr [i] -1是偶数,因此可以通过上述策略将其设为0。因此,奇数元素可以将其大小减小为1。因此,通过遵循上述策略,可以将两个奇数元素设为0,最后对它们进行异或(即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
输出:
Yes
时间复杂度: O(N)
辅助空间复杂度: O(1)