Java BigInteger setBit()方法
java.math.BigInteger.setbit(index) 方法返回一个大整数,其值相当于这个大整数的指定位被设置。该方法计算的是(this | (1<<n)
)。Big-integer的二进制表示法中位于索引n的位将被设置为1。
语法
public BigInteger setbit(int n)
参数: 该方法需要一个参数n
,指的是需要设置的位的索引。
返回值: 该方法在设置了位的位置n后返回BigInteger值。
例外: 当n为负数时,该方法可能会抛出一个ArithmeticException。
例子:
输入: value = 2300 index = 1
输出: 2302
解释:
2300=100011111100的二进制表示法
索引1的位是0,所以设置索引1的位
现在二进制表示成为100011111110
和十进制相当于100011111110是2302
输入: value = 5482549 index = 1
输出: 5482551
下面的程序说明了BigInteger的setBit(index)方法。
// Program to demonstrate setBit() method of BigInteger
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Creating BigInteger object
BigInteger biginteger = new BigInteger("2300");
// Creating an integer i for index
int i = 1;
// Calling setBit() method on bigInteger at index i
// store the return BigInteger
BigInteger changedvalue = biginteger.setBit(i);
String result = "After applying setBit at index " +
i + " of " + biginteger+ " New Value is " + changedvalue;
// Displaying the result
System.out.println(result);
}
}
输出
After applying setBit at index 1 of 2300 New Value is 2302
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#setBit(int)