1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68


/*
** The idea is to calculate each bit of quotient from high to low.
** Using addition to move up bit
**
*/
//After test, there is bug for value -2147483648 (the minimus integer); //as for integer -(-2147483648) is still -2147483648, not 2147483648. //So we need a larger type which could contains value 2147483648 typedef long long_int; //if the sizeof(long) is equal to sizeof(int) in some system, //you may need to use long long instead //typedef long long long_int; int Divide(int dend, int dsor) { long_int dividend = dend; long_int divisor = dsor; int quotient = 0; bool negative = false; //indicate if the final result is negative if (dividend < 0) { negative = true; dividend = -dividend; } if (divisor < 0) { negative = !negative; //negative based on dividend else divisor = -divisor; } while(dividend >= divisor) { long_int addition = divisor; int cur_quotient = 1; while(dividend >= (addition + addition)) { //move up bit addition += addition; cur_quotient <<= 1; // /*equal to*/ cur_quotient += cur_quotient; } quotient += cur_quotient; //prepare for next bit dividend -= addition; } if (negative) quotient = -quotient; return quotient; } #include <stdio.h> int main(int argc, char** argv) { int dividend = 2147483647; int divisor = 3; printf("%d\n", Divide(dividend,divisor)); return 0; }
View Program Text


Test Status