Divide two integers

Source: Internet
Author: User

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

Analysis:

Multiplication, division, and modulo operations are not supported. We can use addition, subtraction, and bitwise operations. A simple idea is to subtract the divisor on dividend and know that the remainder is smaller than the divisor. Then, the number of reductions is the result. Here we can use a method similar to binary search to use power-Level Jump to test how many times dividend is divisor, so as to achieve acceleration. There are two ways to perform power-Level Jump. One is dividend first times the divisor, and the other is dividend first minus the maximum multiple of divisor smaller than dividend. Because we can use bitwise shifts to implement the 2power operation, the second method is faster than the first one, especially when dividend and divisor differ a lot.

Leetcode version:

class Solution {public:    int divide(int dividend, int divisor) {        long long div = (dividend > 0)? dividend:-(long long)dividend;        long long dis = (divisor > 0)? divisor: -(long long)divisor;        int result = 0;        while(div >= dis){            int counter = 0;            while(div >= dis<<counter){                counter++;            }            result += 1<<(counter-1);            div -= dis<<(counter-1);        }        return ((dividend^divisor)>>31)?(-result):result;    }};

Timeout version:

class Solution {public:    int divide(int dividend, int divisor) {        long long div = (dividend > 0)? dividend:-(long long)dividend;        long long dis = (divisor > 0)? divisor: -(long long)divisor;        int result = 0;        while(div >= dis){            long long c = dis;            for(int i = 0; div >= c; i++, c<<i){                div -= c;                result += 1<<i;             }        }        return ((dividend^divisor)>>31)?(-result):result;    }};

 

Divide two 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.