2014-11-17 20 views
0

下面是我在BigInteger的看着在Java中的表達式中使用雙引號時會做什麼?

public static BigInteger factorial(long n) { 
BigInteger result = BigInteger.ONE; 
for (int i = 1; i <= n; i++) 
result = result.multiply(new BigInteger(i + "")); 

return result; 

它是做什麼(我+「」))的例子嗎?

+1

你知道字符串是什麼嗎?你知道如何編寫一個字符串文字嗎?你知道什麼添加一個字符串到非字符串產生?把這些信息放在一起,你會看到'i +「」'做了什麼。 – user2357112

+1

這是**錯誤**的方式來隱式獲取數字的字符串表示形式,從不這樣做。 'String.valueOf()'是這樣做的正確方法。 –

回答

2

這是將int轉換爲String對象的簡短方法。他們這樣做是因爲BigInteger的構造函數沒有收到一個int作爲參數。

你可以看看這裏的Javadoc:https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

由於表達的是內部的,更好的方式必須是:

for (int i = 1; i <= n; i++) 
result = result.multiply(BigInteger.valueOf(i)); 

因爲當你試圖使用該字符串的構造是有用表示大於64位的數字signed int(2^63 - 1)

+1

不是'BigInteger.valueOf(i)'工作嗎? – Justin

+0

你是對的,尋找soruce代碼是最好的方法 –

3

構造函數BigInteger需要String參數,而不是int

i + ""強制iString數據類型,以便它可以傳遞給構造函數。

相關問題