Java BigInteger testBit()方法
java.math.BigInteger.testBit( index ) 方法在指定的位被设置时返回真。此方法计算 (this & (1<<n)) != 0) 。
语法
public boolean testBit(int n)
参数: 该方法需要一个整数类型的参数n,指的是需要测试的位的索引。
返回值: 当且仅当指定的位被设置时,该方法返回真,否则它将返回假。
异常: 当n为负数时,该方法将抛出一个ArithmeticException。
示例
输入 : BigInteger = 2300, n = 4
输出 : true
解释:
2300=100011111100的二进制表示法
索引4的位是1,所以设置它意味着位被设置了
所以方法将返回真
输入 : BigInteger = 5482549 , n = 1
输出 : 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://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#testBit(int)