29. 两数相除 Divide Two Integers
Given two integers dividend
and divisor
, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8
and truncate(-2.7335) = -2
.
Note:
- Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For this problem, assume that your function returns 2^31 − 1 when the division result overflows.
方法:
1.注意溢出,可以转换成负值处理。
2.和divisor倍数比较
public int divide(int dividend, int divisor){ if (divisor == 0) return Integer.MAX_VALUE; if(dividend == 0) return 0; if(divisor == -1){ if(dividend > Integer.MIN_VALUE) return -dividend; return Integer.MAX_VALUE; }else if(divisor == 1){ return dividend; } int result = 0; int sign = -1; if (dividend > 0 && divisor > 0 || dividend < 0 && divisor < 0) sign = 1; if (dividend > 0) dividend = -dividend; if (divisor > 0) divisor = -divisor; while ( dividend<=divisor){ int temp=divisor; int c=1; while(dividend-temp<=temp) { temp=temp<<1; c=c<<1; } dividend-=temp; result+=c; } return sign > 0 ? result : -result; }
参考链接:
https://leetcode.com/problems/divide-two-integers/
https://leetcode-cn.com/problems/divide-two-integers/