Divide two integers
Divide two integers without using multiplication, division and mod operator.
Division is not performed using *,/, or %. You can only add or subtract!
Algorithm ideas:
The addition of each element will time out, for example, dividend = integer. max_value, divisor = 1; therefore, this is not a drop.
Train of Thought 1: it is more efficient than O (N), that is, the binary method;
[Note] handle overflow, negative numbers, and 0;
The divisor doubles each time. When it switches to a greater value than dividend, it records the multiples of growth. Update dividend and increase from divisor.
For example, 12/1, 1-> 2-> 4-> 8-> 16 (16> 12), update dividend to 12-8 = 4. Then divisior increases from 1 to 2 to 4.
The Code is as follows:
Public class solution {public int divide (INT dividend, int divisor) {If (dividend = 0 | divisor = 0) return 0; long absdividend = math. ABS (long) dividend); long absdivisor = math. ABS (long) divisor); If (absdividend <absdivisor) return 0; int res = 0; while (absdividend> = absdivisor) {Long Count = 1; long tem = absdivisor; while (TEM <absdividend) {TEM <= 1; count <= 1;} If (TEM! = Absdivisor) {TEM >>= 1; count >>=1;} res + = count; absdividend-= TEM ;} // This exception or returns res * (dividend <0 ^ divisor <0? (-1): 1 );}}
Idea 2:
Maintain a one-dimensional array multi, multi [I] to store the case where the divisor is doubled, and then subtract the divisor. For more information, see here.
Public class solution {public int divide (INT dividend, int divisor) {If (dividend = 0 | divisor = 1) return dividend; long divid = dividend; long divis = divisor; Boolean neg = false; // process int result = 0 for a classic negative number; If (dividend <0) {neg =! Neg; divid =-divid;} If (divisor <0) {neg =! Neg; divis =-divis;} long [] multi = new long [32]; for (INT I = 0; I <32; I ++) multi [I] = divis <I; for (INT I = 31; I> = 0; I --) {If (divid> = multi [I]) {result + = 1 <I; divid-= multi [I] ;}} return (neg? -1: 1) * result ;}
References:
Http://www.cnblogs.com/jdflyfly/p/3810717.html