Code

#include <stdio.h>

int toggleFifthBit(int n) {
    // Write your code here

    int a;
    a = (1<<5);
    //printf("\n A : %d",a);
    n = n ^ a;
    return n;
}

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

Solving Approach

 

5th bit of N (i.e., flip the bit at position 5: if 0, make it 1; if 1, make it 0).

5   4 3 2 1 0
32 16 8 4 2 1
1  0 0 1 0 0

5th bit is 1.

type 1
0  0 0 1 0 0 - Q
1  0 0 1 0 0 - A

type 2
1  0 0 1 0 0 - Q
0  0 0 1 0 0 - A


5   4 3 2 1 0
32 16 8 4 2 1
0  0 1 0 1 0 = 10
1  0 1 0 1 0 = 10 + 32 = 42


7   6  5   4 3 2 1 0
128 64 32 16 8 4 2 1
0  0  0  1  1 1 1 1 = 31
0  1  0  1  1 1 1 1 = 31 + 64 = 95

7   6  5   4 3 2 1 0
128 64 32 16 8 4 2 1
0  0  0  0  1 1 1 1 = 15
0  0  1  0  1 1 1 1 = 15 + 32 = 47


5   4 3 2 1 0
32 16 8 4 2 1
1  0 0 0 0 0 = 32

Input: 10
Explanation:
Binary representation of 10 is 00001010.
Toggling the 5th bit (position 5) results in 00101010, which is 42 in decimal.
Expected Output: 42
 

Input: 31
Explanation:
Binary representation of 31 is 00011111.
Toggling the 5th bit (position 5) results in 01011111, which is 95 in decimal.
Expected Output: 95
 

Input: 0
Explanation:
Binary representation of 0 is 00000000.
Toggling the 5th bit (position 5) results in 00100000, which is 32 in decimal.
Expected Output: 32

 

 

 

Upvote
Downvote
Loading...

Input

8

Expected Output

40