The link to the problem https://leetcode.com/problems/divide-two-integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution | |
{ | |
public int Divide(int dividend, int divisor) | |
{ | |
var negative = IsResultNegative(dividend, divisor); | |
var dividendPositive = ToPositive(dividend); | |
var divisorPositive = ToPositive(divisor); | |
var resultPositive = DividePositive(dividendPositive, divisorPositive); | |
return FromPositive(resultPositive, negative); | |
} | |
private static uint ToPositive(int input) | |
{ | |
if (input == int.MinValue) | |
{ | |
return int.MaxValue + 1u; | |
} | |
return (uint)Math.Abs(input); | |
} | |
private static int FromPositive(uint input, bool toNegative) | |
{ | |
var limit = toNegative ? int.MaxValue + 1u : int.MaxValue; | |
var result = input > limit ? limit : input; | |
return toNegative ? -(int)result : (int)result; | |
} | |
private static uint DividePositive(uint dividend, uint divisor, uint subResult = 0) | |
{ | |
if (dividend < divisor) | |
return subResult; | |
var divisorTemp = divisor; | |
var newSubResult = 1u; | |
while (dividend >= divisorTemp << 1 && IsSafeToShiftLeft(divisorTemp)) | |
{ | |
divisorTemp <<= 1; | |
newSubResult <<= 1; | |
} | |
return DividePositive(dividend - divisorTemp, divisor, subResult + newSubResult); | |
} | |
private static bool IsSafeToShiftLeft(uint divisorTemp) | |
{ | |
return divisorTemp < 0x80000000; | |
} | |
private static bool IsResultNegative(int dividend, int divisor) | |
{ | |
return dividend < 0 ^ divisor < 0; // XOR operation | |
} | |
} |