2. Bit Toggle

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

xor operator (^) is used for toggling the bit. 
A | B | (A^B)
0 | 0 |    0
0 | 1 |    1
1 | 0 |    1
1 | 1 |    0


if n = 33, whose binary representation is 00100001 and the current 5th bit (position 5 from 0 based index) is 1.
the value of (1<<5) is 00100000 
xor n and 1<<5 => n^(1<<5) gives 00000001 which is 1.

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

 

 

Was this helpful?
Upvote
Downvote