Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Solution Subtraction
- 1234567891011121314151617181920212223242526272829303132public static int divide2(int dividend, int divisor) {if (dividend == 0 || divisor == 0) {return 0;}long a = Math.abs((long) dividend);long b = Math.abs((long) divisor);if (b > a) {return 0;}long sum = 0;long pow = 0;long result = 0;while (a >= b) {pow = 1;sum = b;while (sum + sum <= a) {sum += sum;pow += pow;}a -= sum;result += pow;}result = ((((dividend ^ divisor) >> 31) & 1) == 1) ? -result: result;if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {return Integer.MAX_VALUE;}return (int)result;}
Solution Bit Manipulation
|
|
Fraction to Recurring Decimal
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return “0.5”.
Given numerator = 2, denominator = 1, return “2”.
Given numerator = 2, denominator = 3, return “0.(6)”.
Solution
+The key insight here is to notice that once the remainder starts repeating, so does the divided result.
+You will need a hash table that maps from the remainder to its position of the fractional part. Once you found a repeating remainder, you may enclose the reoccurring fractional part with parentheses by consulting the position from the table.
+The remainder could be zero while doing the division. That means there is no repeating fractional part and you should stop right away.
+Just like the question Divide Two Integers, be wary of edge case such as negative fractions and nasty extreme case such as -2147483648 / -1.
|
|