forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
divideTwoInt.cpp
74 lines (63 loc) · 1.95 KB
/
divideTwoInt.cpp
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
69
70
71
72
73
74
// Source : https://oj.leetcode.com/problems/divide-two-integers/
// Author : Hao Chen
// Date : 2014-06-20
/**********************************************************************************
*
* Divide two integers without using multiplication, division and mod operator.
*
*
**********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int divide(int dividend, int divisor) {
int sign = 1;
long long dvd = dividend;
long long dvs = divisor;
if (dvd<0) {
dvd = -dvd;
sign = -sign;
}
if (dvs<0) {
dvs = -dvs;
sign = -sign;
}
long long bit_num[32];
memset( bit_num, 0, sizeof(bit_num)/sizeof(bit_num[0]) );
int i=0;
long long d = dvs;
bit_num[i] = d;
while( d <= dvd ){
bit_num[++i] = d = d << 1;
}
i--;
unsigned int result = 0;
while(dvd >= dvs){
if (dvd >= bit_num[i]){
dvd -= bit_num[i];
result += (1<<i);
}else{
i--;
}
}
return result * sign;
}
int main()
{
cout << "10/2=" << divide(10, 2) << endl;
cout << "10/3=" << divide(10, 3) << endl;
cout << "10/5=" << divide(10, 5) << endl;
cout << "10/7=" << divide(10, 7) << endl;
cout << "10/10=" << divide(10, 10) << endl;
cout << "10/11=" << divide(10, 11) << endl;
cout << "1/-1=" << divide(1, -1) << endl;
cout << "-1/-1=" << divide(-1, -1) << endl;
cout << "2147483647/1=" << divide(2147483647, 1) << endl;
cout << "-2147483647/1=" << divide(-2147483647, 1) << endl;
cout << "2147483647/-1=" << divide(2147483647, -1) << endl;
cout << "-2147483647/-1=" << divide(-2147483647, -1) << endl;
cout << "2147483647/2=" << divide(2147483647, 2) << endl;
cout << "2147483647/10=" << divide(2147483647, 10) << endl;
cout << "-2147483648/1=" << divide(-2147483648, 1) << endl;
}