"Leetcode" Divide, integers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.