Divide Two Integers

2013.12.7 04:52

Divide two integers without using multiplication, division and mod operator.

Solution:

  Another bit-manipulation problem, integer division. Normally if we calculate x / y (x, y > 0), we'll subtract y from x until y < x. This operation can be accelerated if we subtract x << (..., 2, 1, 0) from y, until x < y, using only log2(x) time.

  Time complexity is O(log(dividend) - log(divisor)), space complexity is O(1).

Accepted code:

 1 // 2RE, 2WA, 1AC
 2 class Solution {
 3 public:
 4     int divide(int dividend, int divisor) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         // 2RE here, -2147483648 is a tricky case
 8         
 9         long long int div1, div2;
10         int s1, s2;
11         long long int base;
12         // 1WA here, $r overflows, must be long long int
13         long long int res, r;
14         
15         s1 = sign(dividend);
16         s2 = sign(divisor);
17         
18         if(s1 * s2 == 0){
19             return 0;
20         }
21         
22         div1 = dividend > 0 ? dividend : -(long long int)dividend;
23         div2 = divisor > 0 ? divisor : -(long long int)divisor;
24         
25         base = div2;
26         r = 1;
27         while(base <= div1){
28             base <<= 1;
29             r <<= 1;
30         }
31         
32         res = 0;
33         while(r > 0){
34             if(div1 >= base){
35                 div1 -= base;
36                 res += r;
37             }
38             base >>= 1;
39             r >>= 1;
40         }
41         
42         if(s1 < 0){
43             res = -res;
44         }
45         if(s2 < 0){
46             res = -res;
47         }
48         
49         // 1WA here, forgot to multiply sign variables
50         return res;
51     }
52 private:
53     int sign(int x){
54         if(x > 0){
55             return 1;
56         }else if(x < 0){
57             return -1;
58         }else{
59             return 0;
60         }
61     }
62 };

 

 posted on 2013-12-07 05:00  zhuli19901106  阅读(348)  评论(0编辑  收藏  举报