# Wrong Answer: Input:(-2147483648, -1) Output:2147483648, Expected:2147483647

• {

class Solution:
# @return an integer
def divide(self, dividend, divisor):

``````    if dividend == 0:
return 0

sign = 1 if(dividend <0 and divisor <0) or (dividend >0 and divisor >0) else -1
dividend = abs(dividend)
divisor = abs(divisor)

ans = 0

while dividend >= divisor:
shift = 0
while ((divisor << shift) <= dividend):
shift +=1

ans += 1<<(shift-1)
dividend -= divisor<<(shift-1)

return ans if (sign==1) else -ans
``````

}

{
Submission Result:
Output: 2147483648
Expected: 2147483647
}

I think my output is correct instead of the expected answer, but my code cannot be accepted. I think it should be some overflow problem. Could someone tell me how can I make this problem? Thanks!

• The maximal positive integer is 2147483657.

• the LC OJ has changed and added this special case, which means your code should take this case into consideration as well.

• It's already stated in the problem description that "If it is overflow, return MAX_INT."

Your output 2147483648 is bigger than MAX_INT, which is 2147483647.
You should return 2147483647 in this case.

• My accepted Solution,it's main idea is similar to yours.

class Solution {
public:
int divide(int dividend, int divisor)
{
long long dividendLong=abs((long long)dividend);
long long divisorLong=abs((long long)divisor);
long long result=0;
while(dividendLong>=divisorLong)
{
unsigned int cnt=0;
while(dividendLong>=divisorLong<<(cnt+1)) cnt++;
dividendLong-=divisorLong<<cnt;
//if(cnt>=31)
//(long long)非常关键，调试了一天
result+=((long long)1<<cnt);
}
//最高符号位异或
result=(dividend>>31)^(divisor>>31)?-result:result;
if(result>INT_MAX||result<INT_MIN)
result=INT_MAX;
return result;

``````}
``````

};

• Why not 2147483647?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.