-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path029-DivideTwoIntegers.cs
36 lines (32 loc) · 1.03 KB
/
029-DivideTwoIntegers.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
//-----------------------------------------------------------------------------
// Runtime: 60ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _029_DivideTwoIntegers
{
public int Divide(int dividend, int divisor)
{
if (divisor == 0) { throw new DivideByZeroException(); }
uint a = dividend > 0 ? (uint)dividend : (uint)-dividend;
uint b = divisor > 0 ? (uint)divisor : (uint)-divisor;
uint result = 0, c = 0;
var index = 0;
while (a >= b)
{
c = b;
for (index = 0; a >= c && c != 0; index++, c *= 2)
{
a -= c;
result += (uint)1 << index;
}
}
return (dividend ^ divisor) >> 31 == -1
? (int)-result
: result > int.MaxValue ? int.MaxValue : (int)result;
}
}
}