[Leetcode] 29. Divide integers

Source: Internet
Author: User

This topic has not been done since there are too many corner case to consider.

1. Divisor equals 0.

2. Dividend equals 0.

3. Is the result negative?

4. When dividend equals Integer.min_value and divisor equals-1, the result would overflow. Convert result to long and then to Integer.

5. Divided by divisor * 2 ^ n to avoid exceeding time limit

6. There is a to convert divisor and dividend to a long to avoid overflow in shift.

7. Constant 1 in Java are compiled as Integer by default.

 Public classSolution { Public intDivideintDividend,intdivisor) {        if(Divisor = = 0) {            returnDividend >= 0?Integer.MAX_VALUE:Integer.MIN_VALUE; }        if(Dividend = = 0) {            return0; }        Booleanisnegative = (Dividend > 0 && divisor < 0) | | (Dividend < 0 && divisor > 0); Longx = Math.Abs ((Long) dividend); Longy = Math.Abs ((Long) divisor); Longresult = 0;  while(x >=y) {intA = 0;  while(x >= (y <<a)) {a++; } A--; Result+= (Long) 1 <<A; X-= y <<A; }        if(Result = = (Long) Integer.max_value + 1) {            returnIsnegative?Integer.MIN_VALUE:Integer.MAX_VALUE; }        returnIsnegative? -(int) Result: (int) result; }}

[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.