Divide two integers

Source: Internet
Author: User

Divide two integers without using multiplication, division and mod operator.

Division is not performed by multiplication, division, or modulo operation. That is to say, only addition and subtraction and bitwise operations can be used. The natural idea is to subtract the divisor each time and determine how many times the divisor is subtracted. This is the result, this will time out when the divisor is large and the divisor is small. Therefore, based on this, we can increase the number of divisor each time and then reduce it until the divisor is greater than the divisor, and then divide the divisor by 2 each time, perform subtraction until the divisor is equal to zero, which can accelerate. In this process, doubling and dividing by 2 can be achieved by bitwise operations.

The Code is as follows:

 1 public int divide(int dividend, int divisor) { 2         int count = 0; 3         long a = Math.abs((long)dividend); 4         long b = Math.abs((long)divisor); 5         boolean isNegative = (dividend ^ divisor) >= 0; 6         long i = 1; 7         for (; a >= b; i<<=1, b <<= 1) { 8             a -= b; 9             count += i;10         }11         for (; i > 0; i>>=1, b >>= 1) {12             if (a >= b) {13                 a -= b;14                 count += i;15             }16         }17         return isNegative ? count : -count;18     }

ACSS 520 Ms

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.