Test instructions: Divide without multiplication take-out operation
Ideas:
1, if the cycle of the factor subtracted from the dividend, then if it is Int_max or int_min divided by 1 , the execution time will be very long
2, the method of improving the time efficiency is used to multiply the factor divisor by 2(can be achieved by the shift, and the results of ret also shifted from 1 continuously doubled), and then compared with dividend, When the value is greater than or equal to dividend, subtract from the dividend, multiply the number of factors into the result, and then subtract less than its general factor in the remaining dividend, using recursive loops
Code:
Package leetcode.doit;
??
public class Dividetwointegers_my {
??
/**
* @param args
*/
public static void Main (string[] args) {
int ret = Divide (2, 3);
SYSTEM.OUT.PRINTLN (ret);
int dividend = 20;
int divisor = 3;
int result = 1;
while (divisor < dividend) {
Divisor <<= 1;
Result <<= 1;
}
if (divisor! = dividend) {
Divisor >>= 1;
Result >>= 1;
}
Dividend-= divisor;
SYSTEM.OUT.PRINTLN (divisor);
}
??
static int divide (int dividend, int divisor) {
int divisor_org=divisor;
if (Dividend < divisor) {
Dividend = 0; Update dividend.
return 0;
}
??
int result = 1;
??
while (divisor < dividend) {
Divisor <<= 1;
Result <<= 1;
}
??
if (divisor! = dividend) {
Divisor >>= 1;
Result >>= 1;
}
??
Dividend-= divisor;
Result =result + divide (dividend,divisor_org);
SYSTEM.OUT.PRINTLN (result);
return result;
}
}
??
??
"Leetcode" Divide, integers