"Leetcode 29" Divide, integers

Source: Internet
Author: User

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

If It is overflow, return max_int.

Test instructions

Achieve division, but do not allow multiplication, division, and modulo operations.

Ideas:

A bit less must appear very low, in fact can be used for the first time dividend minus divisor, the second time with Dividend-divisor minus 2 * divisor, the third time with dividend-3 * divisor minus 4 * divisor ... Until the reduction, then at this time obediently with dividend-(x = 1+2+4+...+2^n) * Divisor minus divisor,dividend-(x+1) * Divisor minus 2 * divisor ... Cycle, count the good number is OK. This problem has a special trick, online a lot of accept code I submit already had to pass (very curious how they did ...) ), can only be manually judged in silence.

C++:

1 classSolution {2  Public:3     intDivideintDividend,intdivisor) {4         5         if(Dividend = =0|| divisor = =0)6             return 0;7         //special judgment, exceeding maximum value should return Max_int8         if(Dividend = =-2147483648&& divisor = =-1)9             return 2147483647;Ten          One         Long LongA = ABS (static_cast<Long Long>(dividend)); A         Long Longb = ABS (static_cast<Long Long>(divisor)); -         Long LongRET =0; -          the          while(A >=b) -         { -             Long Longc =b; -              +              for(inti =0; a >= C; i++) -             { +A-=C; AC <<=1; atRET + =1<<i; -             } -         } -         return((dividend ^ divisor) >> to) ? (-ret): (ret); -     } -};

"Leetcode 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.