为什么它能成功地处理长数据类型的内存大小?

tpgth1q7  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(238)

在数学问题上,我对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 .
但是,以下两种方式:
或者用数学计算代替 longBigInteger ,

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);
}

两者都能输出期望的答案。
如果我能知道原因那就太好了。非常感谢。

vfwfrxfs

vfwfrxfs1#

价值 n * m 正在从中溢出 int 限制,因此你可以施展 n 或者 mlong 为了把乘法的结果变成 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

相关问题