Code

#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;
}

Solving Approach

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:

Index76543210
N = 800001000

We want to flip the switch at Index 5 (which is currently 0, or "OFF").

Step 1: Making a "Pointer" (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. We start with the number 1, which is just a single switch turned ON at Index 0: 00000001.
  2. The << 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.

Step 2: The "Flip" Command (^)

The ^ symbol represents the XOR (Exclusive OR) operation. But instead of confusing math rules, just think of XOR as a smart flipper:

  • If the Mask has a 0, XOR says: "Leave this switch alone."
  • If the Mask has a 1, XOR says: "Flip this switch!"

Step 3: Seeing it in Action

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. At Index 5, the Mask had a 1, so it flipped the original 0 to a 1.
  2. Everywhere else, the Mask had a 0, so the original switches stayed exactly the same.

 

 

Upvote
Downvote
Loading...

Input

8

Expected Output

40