[Leedcode 29] Divide integers

Source: Internet
Author: User

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

If It is overflow, return max_int

 Public classSolution {//Here are a few details to consider://1. Negative questions, see Code, very flattering//2. Because the division can be converted to subtraction, if each time the divisor, very time-consuming, such as 123456/1, need to reduce 123,456 times//Therefore, the reference to the bit operation, the divisor is multiplied by 2 each time, until the divisor is greater than dividend, and then subtracted, attention at this time the results are multiplied//The dividend is then updated, and the divisor is continuously divided by 2, accumulating the result ... //Notice the termination condition: The final difference is less than the original divisor. //In the case of divisor and dividend gap is very large, saving a lot of time//There is one more detail: Notice the overflow problem, so you need to declare all the intermediate variables as long!      Public intDivideintDividend,intdivisor) {       LongNdividend=math.abs ((Long) dividend); LongNdivisor=math.abs ((Long) divisor); intFlag=1; if(dividend<0) flag=-Flag; if(divisor<0) flag=-Flag; LongResult=0; LongRes=1;  while(ndividend>ndivisor) {Ndivisor=ndivisor<<1; Res=res<<1; }        while(Ndividend>=math.abs (Long) (divisor)) {if(ndividend>=ndivisor) {Ndividend=ndividend-Ndivisor; Result+=Res; } ndivisor=ndivisor>>1; Res=res>>1; }       if(flag>0){           if(RESULT&GT;=0X7FFFFFFF)returnInteger.max_value; Else return(int) result; }        Else return-(int) result; }}

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