先决条件: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