Java如何判断整数溢出,溢出后怎么得到提示
问题
在之前刷题的时候遇见一个问题,需要解决int相加后怎么判断是否溢出,如果溢出就返回Integer.MAX_VALUE
解决方案
JDK8已经帮我们实现了Math下,不得不说这个方法是在StackOverflow找到了的,确实比国内一些论坛好多了
加法
publicstaticintaddExact(intx,inty){
intr=x+y;
//HD2-12Overflowiffbothargumentshavetheoppositesignoftheresult
if(((x^r)&(y^r))<0){
thrownewArithmeticException("integeroverflow");
}
returnr;
}
减法
publicstaticintsubtractExact(intx,inty){
intr=x-y;
//HD2-12Overflowifftheargumentshavedifferentsignsand
//thesignoftheresultisdifferentthanthesignofx
if(((x^y)&(x^r))<0){
thrownewArithmeticException("integeroverflow");
}
returnr;
}
乘法
publicstaticintmultiplyExact(intx,inty){
longr=(long)x*(long)y;
if((int)r!=r){
thrownewArithmeticException("integeroverflow");
}
return(int)r;
}
注意long和int是不一样的
publicstaticlongmultiplyExact(longx,longy){
longr=x*y;
longax=Math.abs(x);
longay=Math.abs(y);
if(((ax|ay)>>>31!=0)){
//Somebitsgreaterthan2^31thatmightcauseoverflow
//Checktheresultusingthedivideoperator
//andcheckforthespecialcaseofLong.MIN_VALUE*-1
if(((y!=0)&&(r/y!=x))||
(x==Long.MIN_VALUE&&y==-1)){
thrownewArithmeticException("longoverflow");
}
}
returnr;
}
如何使用?
直接调用是最方便的,但是为了追求速度,应该修改一下,理解判断思路,因为异常是十分耗时的操作,无脑异常有可能超时
写这个的目的
总结一下,也方便告诉他人Java帮我们写好了函数。
到此这篇关于Java如何判断整数溢出,溢出后怎么得到提示的文章就介绍到这了,更多相关Java判断整数溢出内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。