Java BigInteger flipBit()方法
java.math.BigInteger.flipBit(index) 方法返回一个BigInteger,用于翻转BigInteger中的一个特定位。该方法计算(bigInteger ^ (1<<n))。bigInteger的二进制表示法中位于索引n的位将被翻转。也就是说,如果该位是0,它将被转换为1,反之亦然。
语法:
public BigInteger flipBit(int index)
参数: 该方法接受一个整数类型的参数index
,指的是要翻转的位的位置。
返回值: 该方法在翻转index
位置的位后返回bigInteger。
抛出: 当index的值为负时,该方法抛出一个ArithmeticException
。
示例:
输入: value = 2300 , index = 1
输出: 2302
解释:
2300=100011111100的二进制表示法
索引1的位是0,所以翻转索引1的位,它变成了1。
现在二进制表示成为100011111110
和十进制相当于100011111110的是2302
输入: value = 5482549 , index = 5
输出: 5482517
以下程序说明了BigInteger的flipBit(index)方法。
/*
*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);
}
}
输出
After applying flipBit at index 5 of 5482549 New Value is 5482517
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#clearBit(int)