-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution29.cs
50 lines (42 loc) · 1.33 KB
/
Solution29.cs
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
namespace LeetCode.Solutions;
public class Solution29
{
/// <summary>
/// 29. Divide Two Integers
/// <a href="https://leetcode.com/problems/divide-two-integers">See the problem</a>
/// </summary>
public int Divide(int dividend, int divisor)
{
// Handle overflow case
if (dividend == int.MinValue && divisor == -1)
{
return int.MaxValue;
}
// Convert both numbers to long to avoid overflow issues
var dividendLong = Math.Abs((long)dividend);
var divisorLong = Math.Abs((long)divisor);
// Determine the sign of the result
var sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1;
long quotient = 0;
while (dividendLong >= divisorLong)
{
var value = divisorLong;
var multiple = 1L;
while (dividendLong >= value << 1)
{
value <<= 1;
multiple <<= 1;
}
dividendLong -= value;
quotient += multiple;
}
// Apply the sign and handle overflow if any
var result = sign * quotient;
return result switch
{
> int.MaxValue => int.MaxValue,
< int.MinValue => int.MinValue,
_ => (int)result
};
}
}