【发布时间】:2021-02-26 03:31:51
【问题描述】:
这是我在 Leetcode 中为this 问题编写的代码 sn-p。
public static int quotient(int dividend,int divisor){
int n=Math.abs(divisor),count=0,ans=Integer.MAX_VALUE-1;
if(Math.abs(dividend)==1 && Math.abs(divisor)==1){
return dividend*divisor;
}
else if(Math.abs(divisor)==1){
if(dividend<0 && divisor<0)
return Math.abs(dividend);
return dividend*divisor;
}
else if(dividend==0){
return 0;
}
else {
while (true) {
if (n > Math.abs(dividend)) {
ans = count;
break;
} else if (n == Math.abs(dividend)) {
ans = count + 1;
break;
} else {
n += Math.abs(divisor);
count++;
}
}
}
if((dividend<0 && divisor>0) || (dividend>0 && divisor<0))
ans*=-1;
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dividend=sc.nextInt();
int divisor = sc.nextInt();
int ans=quotient(dividend,divisor);
System.out.println(ans);
}
但是这个测试用例的代码失败了,我得到它的输出为-2147483648,预期的输出是2147483648。我尝试使用Math.abs(_),但它也不起作用。
输入:
-2147483648 -1
为什么会这样?请解释一下。
【问题讨论】:
-
Long Integer Java中最大值为
2147483648,最小值为负数2147483648。我不知道为什么会出现这个问题,但也许这会有所帮助。 -
@Yan,不是真的。
-
@Yan,
int/java.lang.Integer最大值正好是+2_147_483_647,而不是+2147483648,它根本不能保存在 32 位 int 中。 -
@fluffy,对不起,这只是一个错字。