28. Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
---
public class Solution { public int divide(int dividend, int divisor) { boolean sign1 = dividend >=0; boolean sign2 = divisor >=0; long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); long rst = 0; while (a >= b) { long c = b; for (int i = 0; c <= a; ++i, c <<= 1) { a -= c; rst += 1 << i; } } if (sign1 ^ sign2) rst = -rst; return (int)rst; } }
浙公网安备 33010602011771号