Java Program to flip a bit in a BigInteger


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

Updated on: 25-Jun-2020

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements