Skip to content

Commit 5d6429d

Browse files
committed
add a case to check if the return value is overflowed, and slight optimization
1 parent 8099be0 commit 5d6429d

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

Diff for: src/divideTwoInt/divideTwoInt.cpp

+17-17
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,26 @@
66
*
77
* Divide two integers without using multiplication, division and mod operator.
88
*
9-
*
9+
* If it is overflow, return MAX_INT.
10+
*
1011
**********************************************************************************/
1112

1213
#include <stdio.h>
1314
#include <string.h>
1415
#include <iostream>
1516
using namespace std;
1617

18+
#define INT_MAX 2147483647
19+
#define INT_MIN (-INT_MAX - 1)
1720

1821
int divide(int dividend, int divisor) {
19-
20-
int sign = 1;
21-
long long dvd = dividend;
22-
long long dvs = divisor;
23-
if (dvd<0) {
24-
dvd = -dvd;
25-
sign = -sign;
26-
}
27-
if (dvs<0) {
28-
dvs = -dvs;
29-
sign = -sign;
30-
}
3122

32-
long long bit_num[32];
33-
memset( bit_num, 0, sizeof(bit_num) );
23+
int sign = (float)dividend / divisor > 0 ? 1 : -1;
24+
unsigned int dvd = dividend > 0 ? dividend : -dividend;
25+
unsigned int dvs = divisor > 0 ? divisor : -divisor;
3426

35-
int i=0;
27+
unsigned int bit_num[32];
28+
unsigned int i=0;
3629
long long d = dvs;
3730
bit_num[i] = d;
3831
while( d <= dvd ){
@@ -50,18 +43,24 @@ int divide(int dividend, int divisor) {
5043
}
5144
}
5245

53-
return result * sign;
46+
//becasue need to return `int`, so we need to check it is overflowed or not.
47+
if ( result > INT_MAX && sign > 0 ) {
48+
return INT_MAX;
49+
}
50+
return (int)result * sign;
5451
}
5552

5653

5754
int main()
5855
{
56+
cout << "0/2=" << divide(0, 2) << endl;
5957
cout << "10/2=" << divide(10, 2) << endl;
6058
cout << "10/3=" << divide(10, 3) << endl;
6159
cout << "10/5=" << divide(10, 5) << endl;
6260
cout << "10/7=" << divide(10, 7) << endl;
6361
cout << "10/10=" << divide(10, 10) << endl;
6462
cout << "10/11=" << divide(10, 11) << endl;
63+
cout << "-1/1=" << divide(1, -1) << endl;
6564
cout << "1/-1=" << divide(1, -1) << endl;
6665
cout << "-1/-1=" << divide(-1, -1) << endl;
6766
cout << "2147483647/1=" << divide(2147483647, 1) << endl;
@@ -71,4 +70,5 @@ int main()
7170
cout << "2147483647/2=" << divide(2147483647, 2) << endl;
7271
cout << "2147483647/10=" << divide(2147483647, 10) << endl;
7372
cout << "-2147483648/1=" << divide(-2147483648, 1) << endl;
73+
cout << "-2147483648/-1=" << divide(-2147483648, -1) << endl;
7474
}

0 commit comments

Comments
 (0)