Set a bit for BigInteger in Java

Java 8Object Oriented ProgrammingProgramming

The setBit() method is used in Java to return a BigInteger whose value is equivalent to this BigInteger with the designated bit set.

Example

 Live Demo

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

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("9");
      // setbit operation using index 3
      bi2 = bi1.setBit(3);
      String res = "Setbit operation on " +bi1+ " at index 3 gives " +bi2;
      System.out.println(res);
   }
}

Output

Setbit operation on 9 at index 3 gives 9
raja
Published on 06-Dec-2018 06:53:27
Advertisements