Java Program to flip a bit in a BigInteger

Java 8Object Oriented ProgrammingProgramming

To flip a bit in a BigInteger in Java, use the flipBit() method. This method returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped.

Example

 Live Demo

import java.math.*;
public class Demo {
   public static void main(String[] args) {
      BigInteger one, two;
      one = new BigInteger("7");
      one = one.flipBit(3);
      System.out.println("Result: " +one);
   }
}

Output

Result: 15

Let us see another example.

Example

 Live Demo

import java.math.*;
public class Demo {
   public static void main(String[] args) {
      BigInteger bi1, bi2;
      bi1 = new BigInteger("8");
      bi2 = bi1.flipBit(1);
      String str = "Flipbit operation on " +bi1+ " at index 1 gives " +bi2;
      System.out.println( str );
   }
}

Output

Flipbit operation on 8 at index 1 gives 10
raja
Published on 06-Dec-2018 06:58:53
Advertisements