Implement the flipBit method, which changes the value of one bit of a given integer to the opposite. We agree that the bits are numbered from the youngest (index 1) to the oldest (index 32).

 public static int flipBit(int value, int bitIndex) { char[] mass = Integer.toBinaryString(value).toCharArray(); int index = bitIndex%32; if(mass[index - 1] == '0') mass[index - 1] = '1'; else mass[index - 1] = '0'; return Integer.parseInt(new String(mass), 2); } 

Gives an error message:

Failed test # 3. Run time error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 30
at Main.flipBit (Main.java:27)
at Main.main (Main.java:14)
at Main.main (Main.java:7)

  • 3
    I don’t know Java, of course, but isn’t it somehow simpler: value^(1<<(bitIndex-1)) ? - PetSerAl
  • let's immediately String.format("%32s", Integer.toBinaryString( value ) ).replace(' ', '0') , cho there :) - zRrr

1 answer 1

To invert a bit at a certain position, you need to move 1 to the desired number of positions to the left (this will be a mask), and then make an XOR with the original number.

 public static long flipBit(int position, long value) { return value ^ 1 << position; } 

Or, you can use the class BitSet

 public static long flipBit(int position, long value) { BitSet bs = BitSet.valueOf(new long[] { value }); bs.flip(position); return bs.toLongArray()[0]; } 

Bits are numbered starting from 0, from right to left.

 long value = 10L; System.out.println(Long.toBinaryString(value)); // 1010 System.out.println(Long.toBinaryString(flipBit(1, value))); // 1000 

Add additional conditions for your task and check for valid values ​​yourself.