java - 如何计算溢出值的输出
问题描述
我在面试中被问到一个与整数溢出有关的问题。问题很简单,但我找不到一个简单的解决方案来计算溢出值的结果。
例如,以下程序应打印 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);
}
}
但是,在这里我们可以使用任何特定的公式或方程式来计算溢出值的输出。这里的数字真的很大,不容易通过人脑快速判断输出。
解决方案
指定它们是long
with L
,因为如果不是你正在做int
乘法,这会导致 an int
which 触及溢出,然后存储到 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
}
推荐阅读
- kubernetes - 为使用上下文根运行的应用程序编写入口规则
- python - 如何在python中处理电报机器人的多个请求?
- nextcloud - Nextcloud 新文件通知
- java - 无法在 BinaryTree 中插入值
- python - 将vimeo链接转换为python中的嵌入链接
- git - Mac git客户端塔不同步存储库中的文件夹
- flutter - 如何从另一个 dart 文件按钮点击事件导航选项卡。我正在使用 Tabmanager ..但它只适用于相同的 dart 文件。我是初学者
- javascript - 从JS中给定路径的目录中读取文件
- reactjs - React:如何根据“If”语句启用 Button
- python - CVXPY - 计算投资组合优化中的交易数量