[英]Why do it succeed to deal with the memory size of long data type like this?
關於數學問題,我是處理 java 中非常大的整數的新手。
這是我對將紙張切割成 1*1 正方形的解決方案的回答。
public static void main(String[] args) {
long result = solve(841251657, 841251657);
System.out.println(result);
}
static long solve(int n, int m) {
long r = n*m - 1;
return r;
}
output 為1810315984
,與預期的 output 707704350405245648
。
但是,以下兩種方式:
要么用BigInteger
代替long
的數學計算,
static long solve(int n, int m) {
BigInteger r = BigInteger.valueOf(n).multiply(BigInteger.valueOf(m));
return r.longValue() - 1;
}
或手動插入輸入(不確定是否是實際原因),
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long m = in.nextLong();
long n = in.nextLong();
long cuts = m*n-1;
System.out.println(cuts);
}
output 都可以得到預期的答案。
如果我能知道原因,那就太好了。 太感謝了。
n * m
的值從int
limit 溢出,因此您可以將n
或m
之一轉換為long
,以便將乘法的結果轉換為long
。
public class Main {
public static void main(String[] args) {
long result = solve(841251657, 841251657);
System.out.println(result);
}
static long solve(int n, int m) {
long r = (long)n * m - 1;
return r;
}
}
Output:
707704350405245648
重要的是要知道,當int
的值溢出時,它會從其最小限制重新開始,例如
public class Main {
public static void main(String[] args) {
int x = Integer.MIN_VALUE;
System.out.println(Integer.MIN_VALUE);
System.out.println(x + 1);
System.out.println(x + 2);
}
}
Output:
-2147483648
-2147483647
-2147483646
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.