1. Think of the XOR operation, 

It only gives a 1 when the inputs A and B are different. This means 1 XOR 1 is 0 and 0 XOR 1 is 1, This means that we can invert (Toggle) the value of A by XOR-ing with 1.
2. What about the other bits? If we XOR 1 with 0 we get 1 and XOR 0 with 0 we get 0. This means that to avoid flipping all the other values, we need to make sure that the other bits are zero.
3. Procedure, Int 1 = 0b000001, Then we left shift it to move the one to the index we want, then we XOR the register to toggle the bit and leave all others untouched!
4. Solution. Reg ^= (1<<n);

Code

#include <stdio.h>

int toggleFifthBit(int n) {
    // Write your code here
    n ^=(1<<5);
    return n;
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%d", toggleFifthBit(n));
    return 0;
}

 

 

Upvote
Downvote
Loading...

Input

8

Expected Output

40