Task:

Implement the flipBit method, which changes the value of one bit of a given integer to the opposite. This task is relevant, for example, when working with bit fields.

We agree that the bits are numbered from the youngest (index 1) to the oldest (index 32).

Sample I / O:

Sample Input: 0 1 Sample Output: 1 

My decision:

 public static int flipBit(int value, int bitIndex) { return value ^ bitIndex; // put your implementation here } 

What is wrong with my decision? Checked on BitwiseCmd . It seems everything is correct.

    1 answer 1

    Understand what it is. The answer will be:

     public static int flipBit(int value, int bitIndex) { return value ^ (1 << bitIndex-1); // put your implementation here } 

    Decision by points:

    1. bitIndex-1 , since numbering starts from zero.
    2. (1 << bitIndex-1) - here we shift the unit to the left by the required number of bits (this is the number of bitIndex-1 )
    3. value ^ (1 << bitIndex-1) - we change the necessary bit, because, for example, with 01011011101^0001 we get 01001011101 .