當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java BigInteger flipBit()用法及代碼示例


先決條件:BigInteger基礎
java.math.BigInteger.flipBit(index)方法返回一個BigInteger,該值用於翻轉BigInteger中的特定位位置。此方法計算(bigInteger ^(1

用法:

public BigInteger flipBit(int index)

參數:該方法接受一個整數類型的參數索引,表示要翻轉的位的位置。


返回值:該方法在位置索引處翻轉bigInteger後返回其值。

拋出:當index的值為負時,該方法拋出ArithmeticException。

例子:

Input: value = 2300 , index = 1
Output: 2302
Explanation:
Binary Representaion of 2300 = 100011111100
bit at index 1 is 0 so flip the bit at index 1 and it becomes 1. 
Now Binary Representation becomes 100011111110
and Decimal equivalent of 100011111110 is 2302

Input: value = 5482549 , index = 5
Output: 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)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 BigInteger flipBit() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。