【问题标题】:Why do it succeed to deal with the memory size of long data type like this?为什么像这样处理长数据类型的内存大小会成功?
【发布时间】:2021-01-04 10:08:07
【问题描述】:

在数学问题方面,我不熟悉在 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);
}

都可以输出预期的答案。

如果我能知道原因就太好了。非常感谢。

【问题讨论】:

  • 您的方法接受ints 并乘以ints。 int 是带符号的 32 位数字。它溢出了。
  • static long solve(int n, int m) 更改为static long solve(long n, long m)
  • 哦,我明白了。谢谢大家!

标签: java memory-management


【解决方案1】:

n * m 的值从int 限制溢出,因此您可以将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;
    }
}

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多