下面是我在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;
它是做什麼(我+「」))的例子嗎?
下面是我在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;
它是做什麼(我+「」))的例子嗎?
這是將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)
不是'BigInteger.valueOf(i)'工作嗎? – Justin
你是對的,尋找soruce代碼是最好的方法 –
構造函數BigInteger
需要String
參數,而不是int
。
i + ""
強制i
到String
數據類型,以便它可以傳遞給構造函數。
你知道字符串是什麼嗎?你知道如何編寫一個字符串文字嗎?你知道什麼添加一個字符串到非字符串產生?把這些信息放在一起,你會看到'i +「」'做了什麼。 – user2357112
這是**錯誤**的方式來隱式獲取數字的字符串表示形式,從不這樣做。 'String.valueOf()'是這樣做的正確方法。 –