Home > Backend Development > C++ > What is the binary array after M range switching operations?

What is the binary array after M range switching operations?

王林
Release: 2023-09-04 11:49:06
forward
1411 people have browsed it

What is the binary array after M range switching operations?

Here we will see a problem. We have a binary array. It has n elements. Each element is either 0 or 1. Initially, all elements are 0. Now we will provide the M command. Each command will contain a start and end index. So command(a, b) means that the command will be applied from the element at position a to the element at position b. This command will toggle the value. So it switches from ath index to bth index. The question is simple. Examine algorithms to get an idea.

Algorithm

toggleCommand(arr, a, b)

Begin
   for each element e from index a to b, do
      toggle the e and place into arr at its position.
   done
End
Copy after login

Example

#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);
}
Copy after login

Output

0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1 1 1 1 0
Copy after login

The above is the detailed content of What is the binary array after M range switching operations?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template