
这里我们会看到一个问题。我们有一个二进制数组。它有n个元素。每个元素要么是 0,要么是 1。最初,所有元素都是 0。现在我们将提供 M 命令。每个命令将包含开始和结束索引。所以 command(a, b) 表示该命令将从位置 a 的元素应用到位置 b 的元素。该命令将切换值。所以它会从 ath 索引切换到 bth 索引。这个问题很简单。检查算法以获得概念。
Begin
for each element e from index a to b, do
toggle the e and place into arr at its position.
done
End#include <iostream>
using namespace std;
void toggleCommand(int arr[], int a, int b){
for(int i = a; i <= b; i++){
arr[i] ^= 1; //toggle each bit in range a to b
}
}
void display(int arr[], int n){
for(int i = 0; i<n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int n = sizeof(arr)/sizeof(arr[0]);
display(arr, n);
toggleCommand(arr, 3, 6);
toggleCommand(arr, 8, 10);
toggleCommand(arr, 2, 7);
display(arr, n);
}0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0
以上就是M个范围切换操作后的二进制数组是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号