[英]How to add leadings Zeros to a BigInteger?
我想將前導零添加到 BigInt,如果 BigInt 的位數少於 10 位,則應添加填充零,我必須稍后使用數字進行計算。
到目前為止,這是我的解決方案:
BigInteger bankAccountNumber = new BigInteger("999999999");
BigInteger zero = new BigInteger("10000000");
public void checksum(){
if(bankAccountNumber.toString().length()<10){
while(bankAccountNumber.toString().length()<10){
}
System.out.println(bankAccountNumber);
}
System.out.println(bankAccountNumber.toString().length());
}
我的問題是我無法想出一個方法,其中包括 bankAccountNumber 是一個帶前導 0 的實數,因為我必須稍后將 Number 與另一個 BigInt 組合,這應該包括前導零,我得到的只是一個帶前導的輸出零,但我不能用那個計算,所以這就是我的問題,謝謝你的幫助。
警告:正如一些評論已經指出的那樣,您在這里從根本上應用了錯誤的方法。 如果“加 1”對某件事沒有意義,那么它就不是數字。 將 1 添加到銀行帳戶不會做任何明智的事情,因此,您最有可能將其存儲為 String 。 除了擴展Number
的 class 以外的任何東西。
BigInteger 不是那樣工作的。 它不是圍繞字符串的輕包裝。 您不能向其添加前導零。
相反,在打印BigInteger 時(將其從其標准的 memory 表示形式轉換為一堆字符,例如向用戶顯示),您指示要如何執行此操作,並且作為其中的一部分,您可以說: ...如果需要,用零填充。
BigInteger example = BigInteger.ONE;
String ex = String.format("This is the number: %012d", example);
System.out.println(ex);
這將打印This is the number: 000000000001
,如您所願。 %012d
is string-format-ese for: "I want to print an integer number ( d
), take at least 12 character slots ( 12
), and if 12 is larger than the number of chars needed to render example
, pad it用零 ( 0
) 輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.