Skip to content

Commit 5faf67a

Browse files
committed
整数除法
1 parent 683eeef commit 5faf67a

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

lcof2/剑指 Offer II 001. 整数除法/Solution.cpp

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,66 @@ class Solution {
2323
}
2424
return sign ? ans : -ans;
2525
}
26-
};
26+
};
27+
28+
#include <iostream>
29+
#include <climits>
30+
31+
using namespace std;
32+
33+
class Solution
34+
{
35+
public:
36+
int divide(int a, int b)
37+
{
38+
if (a == INT_MIN && b == -1)
39+
return INT_MAX;
40+
int negative = 0, ans = 0, flag = 0;
41+
if (a < 0)
42+
{
43+
negative++;
44+
if (a == INT_MIN)
45+
{
46+
a = INT_MAX;
47+
flag = 1;
48+
}
49+
else
50+
{
51+
a = -a;
52+
}
53+
}
54+
if (b < 0)
55+
{
56+
negative++;
57+
b = -b;
58+
}
59+
while (a >= b)
60+
{
61+
int d = b, c = 1;
62+
while (d < INT_MAX >> 1 && (d + d <= a))
63+
{
64+
d += d;
65+
c += c;
66+
}
67+
a -= d;
68+
ans += c;
69+
if (flag)
70+
{
71+
a += 1;
72+
flag = 0;
73+
}
74+
}
75+
return negative == 1 ? -ans : ans;
76+
}
77+
};
78+
79+
int main()
80+
{
81+
Solution solution;
82+
int a = INT_MIN;
83+
int b = 1;
84+
int result = solution.divide(a, b);
85+
cout << "Result of " << a << " divided by " << b << " is: " << result << endl;
86+
87+
return 0;
88+
}

0 commit comments

Comments
 (0)