📌  相关文章
📜  最小化数组元素的按位XOR,使数组之和至少为K所需的值为1

📅  最后修改于: 2021-05-19 19:22:37             🧑  作者: Mango

给定一个由n个正整数和一个正整数K组成的数组arr [] ,任务是对数组元素的最小按位XOR进行计数,所需的位数为1 ,以使数组的总和至少为K。

例子:

方法:可以使用以下事实解决给定的问题:1的按位XOR与偶数元素将元素增加1
请按照以下步骤解决问题:

  • 找到给定数组arr []的总和,并将其存储在变量S中
  • 计算数组中偶数元素的数量,并将其存储在变量中,例如E。
  • 如果S大于或等于K ,则打印0
  • 否则,如果S + E的值小于K ,则打印-1
  • 否则,打印(K – S)值,因为需要将数组元素的按位XOR的最小数量为1。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find minimum number
// of Bitwise XOR of array elements
// with 1 required to make sum of
// the array at least K
int minStepK(int arr[], int N, int K)
{
    // Stores the count of
    // even array elements
    int E = 0;
 
    // Stores sum of the array
    int S = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Increment sum
        S += arr[i];
 
        // If array element is even
        if (arr[i] % 2 == 0)
 
            // Increase count of even
            E += 1;
    }
 
    // If S is at least K
    if (S >= K)
        return 0;
 
    // If S + E is less than K
    else if (S + E < K)
        return -1;
 
    // Otherwise, moves = K - S
    else
        return K - S;
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 1, 0, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 4;
    cout << minStepK(arr, N, K);
 
    return 0;
}


Python3
# Python 3 program for the above approach
 
# Function to find minimum number
# of Bitwise XOR of array elements
# with 1 required to make sum of
# the array at least K
def minStepK(arr, N, K):
 
    # Stores the count of
    # even array elements
    E = 0
 
    # Stores sum of the array
    S = 0
 
    # Traverse the array arr[]
    for i in range(N):
 
        # Increment sum
        S += arr[i]
 
        # If array element is even
        if (arr[i] % 2 == 0):
 
            # Increase count of even
            E += 1
 
    # If S is at least K
    if (S >= K):
        return 0
 
    # If S + E is less than K
    elif (S + E < K):
        return -1
 
    # Otherwise, moves = K - S
    else:
        return K - S
 
# Driver Code
if __name__ == "__main__":
 
    arr = [0, 1, 1, 0, 1]
    N = len(arr)
    K = 4
    print(minStepK(arr, N, K))
 
    # This code is contributed by ukasp.


输出:
1

时间复杂度: O(N)
辅助空间: O(1)