1. Question
2. Answer 2.1. method 1
The question requires that multiplication, division, and Division operations cannot be used, but we canDivision is transferred to the logarithm Field.
$ \ Frac {A} {B} = e ^ {\ frac {LNA} {LNB} = e ^ {LNA-LNB} $
In this way, it is converted to exponential, logarithm, and subtraction operations. Because we can only take the logarithm of a positive integer, we must first take the absolute values of both numbers, and then add the symbol.
At the same time, the question must only store 32-bit signed integers. Therefore, when the data exceeds the upper boundary, special processing is required.
class Solution {public: int divide(int dividend, int divisor) { if(dividend == 0) return 0; double a = fabs(dividend); double b = fabs(divisor); long result = exp(log(a) - log(b)); if ((dividend < 0) ^ (divisor < 0)) result = -result; if (result > INT_MAX) result = INT_MAX; return result; }};
2.2. method 2
Shift operation. See the following example:
$10 \ implies 2 ^ 1*3 + 2 ^ 0*3 \ To \ frac {10} {3} = 2 ^ 1 + 2 ^ 0 = 3 $
$10 \ implies 2 ^ 2*2 + 2 ^ 0*2 \ To \ frac {10} {2} = 2 ^ 2 + 2 ^ 0 = 5 $
$10 \ implies 2 ^ 3*1 + 2 ^ 1*1 \ To \ frac {10} {3} = 2 ^ 3 + 2 ^ 1 = 10 $
We can break down the divisor. Take 10 and 3 as an example. First we determine the maximum coefficient of 3, $10> 32 ^ 1 $ & $10 <32 ^ 2 $, so the maximum coefficient is 2. Then we subtract $3 from 10.2 ^ 1 $, continue the previous process, $4> 32 ^ 0 $ & $4 <3*2 ^ 1 $, the second higher coefficient of 2 is 1. We cyclically perform this process until the final number is less than the divisor, and the sum of all the coefficients before the divisor is required.
Class solution {public: int divide (INT dividend, int divisor) {long a = labs (dividend); // long data occupies 8 bytes, labs () the function calculates the absolute value of long B = labs (divisor); long temp = B; long result = 0; long CNT = 1; while (A> = B) {CNT = 1; temp = B; while (A >=( temp <1) {temp = temp <1; CNT = CNT <1; // represents the coefficients before the divisor} A-= temp; Result + = CNT;} If (dividend <0) ^ (divisor <0) Result =-result; if (result> int_max) Result = int_max; // int_max = 2 ^ 32-1 return result ;*/}};
For more information, see seniusen 」!
Leetcode 29 -- Division of two numbers