繁体   English   中英

为什么像这样处理长数据类型的 memory 大小会成功?

[英]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 溢出,因此您可以将nm之一转换为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM