首页 > 解决方案 > 如何计算溢出值的输出

问题描述

我在面试中被问到一个与整数溢出有关的问题。问题很简单,但我找不到一个简单的解决方案来计算溢出值的结果。

例如,以下程序应打印 1000 作为输出,但由于整数溢出而打印 5。

public class IntegerOvewflow {

    /**
     * Java does not have target typing, a language feature wherein the type of the
     * variable in which a result is to be stored influences the type of the
     * computation.
     * 
     * @param args
     */
    public static void main(String[] args) {
        final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
        final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
        System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);

    }
}

但是,在这里我们可以使用任何特定的公式或方程式来计算溢出值的输出。这里的数字真的很大,不容易通过人脑快速判断输出。

标签: javainteger-overflow

解决方案


指定它们是longwith L,因为如果不是你正在做int乘法,这会导致 an intwhich 触及溢出,然后存储到 along

public static void main(String[] args) {
    final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000L;
    final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
    System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);   // 1000
}

退房:https ://ideone.com/5vHjnH


推荐阅读