Java中的 BigInteger testBit() 方法
先决条件: BigInteger 基础
当且仅当设置了指定位时, Java.math.BigInteger.testBit( index )方法才返回 true。此方法计算(this & (1<
句法:
public boolean testBit(int n)
参数:该方法接受一个整数类型的参数n ,该参数是指需要测试的位的索引。
返回值:当且仅当设置了指定位时,该方法才返回 true,否则返回 false。
异常:当 n 为负数时,该方法将抛出ArithmeticException 。
例子:
Input: BigInteger = 2300, n = 4
Output: true
Explanation:
Binary Representation of 2300 = 100011111100
bit at index 4 is 1 so set it means bit is set
so method will return true
Input: BigInteger = 5482549 , n = 1
Output: false
下面的程序说明了 BigInteger 的 testBit() 方法。
// Program to demonstrate the testBit()
// method of BigInteger
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Creating a BigInteger object
BigInteger biginteger = new BigInteger("2300");
// Creating an int i for index
int i = 3;
boolean flag = biginteger.testBit(i);
String result = "The bit at index " + i + " of " +
biginteger + " is set = " + flag;
// Displaying the result
System.out.println(result);
}
}
输出:
The bit at index 3 of 2300 is set = true
参考: https: Java/math/BigInteger.html#testBit(int)