forked from haoel/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdivideTwoInt.cpp
More file actions
Latest commit
74 lines (64 loc) · 2.26 KB
/
Copy pathdivideTwoInt.cpp
File metadata and controls
74 lines (64 loc) · 2.26 KB
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.
*
* If it is overflow, return MAX_INT.
*
**********************************************************************************/
#include<stdio.h>
#include<string.h>
#include<iostream>
usingnamespacestd;
#defineINT_MAX2147483647
#defineINT_MIN (-INT_MAX - 1)
intdivide(int dividend, int divisor) {
int sign = (float)dividend / divisor > 0 ? 1 : -1;
unsignedint dvd = dividend > 0 ? dividend : -dividend;
unsignedint dvs = divisor > 0 ? divisor : -divisor;
unsignedint bit_num[33];
unsignedint i=0;
longlong d = dvs;
bit_num[i] = d;
while( d <= dvd ){
bit_num[++i] = d = d << 1;
}
i--;
unsignedint result = 0;
while(dvd >= dvs){
if (dvd >= bit_num[i]){
dvd -= bit_num[i];
result += (1<<i);
}else{
i--;
}
}
//becasue need to return `int`, so we need to check it is overflowed or not.
if ( result > INT_MAX && sign > 0 ) {
returnINT_MAX;
}
return (int)result * sign;
}
intmain()
{
cout << "0/2=" << divide(0, 2) << endl;
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 << "-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;
cout << "-2147483648/-1=" << divide(-2147483648, -1) << endl;
}