#include <stdio.h>
int toggleFifthBit(int n) {
// Write your code here
n ^= (1 << 5); // Toggle bit n
return n;
}
int main() {
int n;
scanf("%d", &n);
printf("%d", toggleFifthBit(n));
return 0;
}Bitwise operations can feel abstract, so let's use a visual analogy. Think of your integer as a row of light switches, numbered from right to left starting at zero.
Let's say your input number N is 8. In binary, 8 looks like this: 00001000.
Let's line those bits up with their 0-based indexes:
| Index | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| N = 8 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
We want to flip the switch at Index 5 (which is currently 0, or "OFF").
1 << 5)To flip a specific switch without touching the others, we need a tool that points only to the 5th switch. That's what (1 << 5) does.
1, which is just a single switch turned ON at Index 0: 00000001.<< 5 command means "shift that ON switch 5 spots to the left."Now, our "Pointer" (called a Mask) looks like this: 00100000
Notice that there is a 1 only at Index 5. Everywhere else is a 0.
^)The ^ symbol represents the XOR (Exclusive OR) operation. But instead of confusing math rules, just think of XOR as a smart flipper:
0, XOR says: "Leave this switch alone."1, XOR says: "Flip this switch!"Let's stack our original number and our mask on top of each other, just like an addition problem, and apply the XOR rules:
Index: 7 6 5 4 3 2 1 0
---------------------------
Original: 0 0 0 0 1 0 0 0 (This is 8)
Mask: ^ 0 0 1 0 0 0 0 0 (This is 1 << 5, or 32)
---------------------------
Result: 0 0 1 0 1 0 0 0 (This is 40)
Look at what happened:
1, so it flipped the original 0 to a 1.0, so the original switches stayed exactly the same.
Input
8
Expected Output
40