1. 程式人生 > 實用技巧 >29. 兩數相除 Divide Two Integers

29. 兩數相除 Divide Two Integers

Given two integersdividendanddivisor, divide two integers without using multiplication, division, and mod operator.

Return the quotient after dividingdividendbydivisor.

The integer division should truncate toward zero, which means losing its fractional part. For example,truncate(8.345) = 8andtruncate(-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 functionreturns 2^31− 1 when the division resultoverflows.

方法:

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/