#29 Divide integers

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/divide-two-integers/

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

If It is overflow, return max_int.

int divide (int dividend, int divisor) {    if (dividend = = Int_min && Divisor = =-1)   //divisor is-2147483648 divisor is-1, Quotient overflow return int_max;int quotient = 0;int flag = (Dividend>0&&divisor>0 | | dividend<0&&divisor <0)? 1: -1;unsigned int a = dividend > 0? Dividend:-dividend;   Unsigned integer prevents 2147483648 to overflow after absolute value unsigned int b = divisor > 0? Divisor:-divisor;    unsigned int tmp = A;    int digit = 0;          The number of Bits    while (tmp >= b) {  //the number of bits of the quotient        ++digit;        TMP >>= 1;    }    while (digit--) {    //written calculation process similar to division, starting from the highest bit in addition to calculating the number of the quotient of the number of digits        unsigned int divi = b << digit;        After the divisor is 0 so that except dividend get single digit        quotient = (quotient << 1) + (a >= divi? 1:0);       After the quotient shift of the high position to be weighted (left Shift weighted 2)        a = a >= divi? a-divi:a;    }    if (flag < 0)        quotient =-quotient;    return quotient;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

#29 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.