-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathDivideTwoIntegers.cs
55 lines (48 loc) · 3.11 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Source : https://leetcode.com/problems/divide-two-ints/
// Author : codeyu
// Date : 2016年10月14日 17:11:21
/**********************************************************************************
*
*
* Divide two ints without using multiplication, division and mod operator.
*
*
* If it is overflow, return MAX_INT.
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution029
{
public static int Divide(int dividend, int divisor)
{
//handle special cases
if(divisor==0) return int.MaxValue;
if(divisor==-1 && dividend == int.MinValue)
return int.MaxValue;
//get positive values
long pDividend = Math.Abs((long)dividend);
long pDivisor = Math.Abs((long)divisor);
int result = 0;
while(pDividend>=pDivisor){
//calculate number of left shifts
int numShift = 0;
while(pDividend>=(pDivisor<<numShift)){
numShift++;
}
//dividend minus the largest shifted divisor
result += 1<<(numShift-1);
pDividend -= (pDivisor<<(numShift-1));
}
if((dividend>0 && divisor>0) || (dividend<0 && divisor<0)){
return result;
}else{
return -result;
}
}
}
}