Tuesday, June 9, 2015

Leetcode: Divide Two Integers

June 4, 2015
this website provided a very clear explanation using math formula. Great explanation:
C# code:
/*
* first time using uint in C# - June 4, 2015
* The sbyte data type is an 8-bit signed integer.
The byte data type is an 8-bit unsigned integer.
The short data type is a 16-bit signed integer.
The ushort is a 16-bit unsigned integer.
The int data type is a 32-bit signed integer.
The uint is a 32-bit unsigned integer.
The long data type is a 64-bit signed integer.
The ulong is a 64-bit unsigned integer.
The char data type is a Unicode character (16 bits).
The float data type is a single-precision floating point.
The double data type is a double-precision floating point.
The bool data type is a Boolean (true or false).
The decimal data type is a decimal type with 28 significant digits (typically used for financial purposes).
*/
static int divide3( int dividend, int divisor) {
int result = 0;
bool sign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
uint a = (uint)(dividend >= 0 ? dividend : -dividend);
uint b = (uint)(divisor >= 0 ? divisor : -divisor);
/*
* Try to figure out what we are doing in loops:
*
*/
while (a >= b) {
int multi = 1;
uint bb = b;
while (a >= bb) {
a -= bb;
result += multi;
if (bb < int.MaxValue >> 1)
{
bb += bb;
multi += multi;
}
}
}
if (sign) return -result;
else return result;
}

No comments:

Post a Comment