为什么这样处理long数据类型的内存大小就成功了?
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;
}
输出为1810315984
,与707704350405245648
的预期输出相差甚远。
但是,以下两种方式:
要么将long
的数学计算替换为BigInteger
,
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);
}
都能输出预期的答案
如果能知道原因就好了。非常感谢。
n * m
的值从 int
限制溢出,因此您可以将 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;
}
}
输出:
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);
}
}
输出:
-2147483648
-2147483647
-2147483646
关于数学问题,我刚开始处理 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;
}
输出为1810315984
,与707704350405245648
的预期输出相差甚远。
但是,以下两种方式:
要么将long
的数学计算替换为BigInteger
,
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);
}
都能输出预期的答案
如果能知道原因就好了。非常感谢。
n * m
的值从 int
限制溢出,因此您可以将 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;
}
}
输出:
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);
}
}
输出:
-2147483648
-2147483647
-2147483646