Friday, September 5, 2025
HomeLanguagesJavaBigInteger flipBit() Method in Java

BigInteger flipBit() Method in Java

Prerequisite: BigInteger BasicsĀ 
The java.math.BigInteger.flipBit(index) method returns a BigInteger which is used to flip a particular bit position in a BigInteger. This method Computes (bigInteger ^ (1<<n)). The bit at index n of binary representation of the bigInteger will be flipped. That is, if the bit position is 0 it will be converted to 1 and vice versa.
Syntax:Ā 
Ā 

public BigInteger flipBit(int index)

Parameter:The method accepts one parameter index of integer type and refers to the position of the bit to be flipped.
Return Value: The method returns the bigInteger after flipping its bit at position index.
Throws: The method throws an ArithmeticException when the value of index is negative.
Examples:Ā 
Ā 

Input: value = 2300 , index = 1
Output: 2302
Explanation:
Binary Representation of 2300 = 100011111100
bit at index 1 is 0 so flip the bit at index 1 and it becomes 1. 
Now Binary Representation becomes 100011111110
and Decimal equivalent of 100011111110 is 2302

Input: value = 5482549 , index = 5
Output: 5482517

Below program illustrate flipBit(index) method of BigInteger.
Ā 

Java




/*
*Program Demonstrate flipBit() method of BigInteger
*/
import java.math.*;
Ā 
public class GFG {
Ā 
Ā Ā Ā Ā public static void main(String[] args)
Ā Ā Ā Ā {
Ā Ā Ā Ā Ā Ā Ā Ā // CreatingĀ  BigInteger object
Ā Ā Ā Ā Ā Ā Ā Ā BigInteger biginteger = new BigInteger("5482549");
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā // Creating an int i for index
Ā Ā Ā Ā Ā Ā Ā Ā int i = 5;
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā // Call flipBit() method on bigInteger at index i
Ā Ā Ā Ā Ā Ā Ā Ā // store the return BigInteger
Ā Ā Ā Ā Ā Ā Ā Ā BigInteger changedvalue = biginteger.flipBit(i);
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā String result = "After applying flipBit at index " + i +
Ā Ā Ā Ā Ā Ā Ā Ā " of " + biginteger+ " New Value is " + changedvalue;
Ā 
Ā Ā Ā Ā Ā Ā Ā Ā // Print result
Ā Ā Ā Ā Ā Ā Ā Ā System.out.println(result);
Ā Ā Ā Ā }
}


Output:Ā 

After applying flipBit at index 5 of 5482549 New Value is 5482517

Ā 

Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#clearBit(int)
Ā 

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS