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


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


java.math.BigInteger.longValue()將此BigInteger轉換為長值。如果此函數返回的值太大而無法容納長值,則它將僅返回低階64位。這種轉換很可能會丟失有關BigInteger值的整體大小的信息。此方法還可以返回帶有相反符號的結果。

用法:

public long longValue()

返回值:該方法返回一個long值,該值代表此BigInteger的long值。


例子:

Input: BigInteger1=3214558191
Output: 3214558191
Explanation: BigInteger1.longValue()=3214558191.

Input: BigInteger1=32145535361361525377
Output: -4747952786057577855
Explanation: BigInteger1.longValue()=-4747952786057577855. This BigInteger is too big for 
longValue so it is returning lower 64 bit.

示例1:以下示例程序旨在說明BigInteger類的longValue()方法

// Java program to demonstrate longValue() method of BigInteger 
  
import java.math.BigInteger; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Creating 2 BigInteger objects 
        BigInteger b1, b2; 
  
        b1 = new BigInteger("3214553537"); 
        b2 = new BigInteger("76137217351"); 
  
        // apply longValue() method 
        long longValueOfb1 = b1.longValue(); 
        long longValueOfb2 = b2.longValue(); 
  
        // print longValue 
        System.out.println("longValue of "
                           + b1 + " : " + longValueOfb1); 
        System.out.println("longValue of "
                           + b2 + " : " + longValueOfb2); 
    } 
}
輸出:
longValue of 3214553537 : 3214553537
longValue of 76137217351 : 76137217351

示例2:當long返回值對於long值而言太大時。

// Java program to demonstrate longValue() method of BigInteger 
  
import java.math.BigInteger; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // Creating 2 BigInteger objects 
        BigInteger b1, b2; 
  
        b1 = new BigInteger("32145535361361525377"); 
        b2 = new BigInteger("7613721535372632367351"); 
  
        // apply longValue() method 
        long longValueOfb1 = b1.longValue(); 
        long longValueOfb2 = b2.longValue(); 
  
        // print longValue 
        System.out.println("longValue of "
                           + b1 + " : " + longValueOfb1); 
        System.out.println("longValue of "
                           + b2 + " : " + longValueOfb2); 
    } 
}
輸出:
longValue of 32145535361361525377 : -4747952786057577855
longValue of 7613721535372632367351 : -4783767069412450057

參考:
BigInteger longValue() Docs



相關用法


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