Leetcode-divdend two integers

Source: Internet
Author: User

Question:

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

 

Train of Thought Analysis

In the binary method, the divisor is multiplied, and the result is also doubled until the divisor value is greater than the divisor value. Then, the divisor is used to subtract the divisor and finally increase to a value smaller than the divisor value to obtain the result recursively.

Example: 123/4

4 <123 4*2 = 8 <123 8*2 = 16> 123 16*2 = 32 <123

32*2 = 64 <123 64*2 = 128> 123 The result is increased by 64/4 = 16.

Use 123-64 = 59 and recursively obtain the result again. The final result is 59/4 = 14, and the remainder is 3 <4 discard.

Therefore, the final value is 16 + 14 = 30.

 

Code:

 1 public Solution{ 2 public: 3     long long  interDivide(unsigned long long dividend, 4                       unsigned long long divisor){ 5           if(dividend<divisor) return 0; 6                7           long long result=1; 8           unsigned long long tmp=divisor,left; 9           10           while(tmp<=dividend){11                  left=dividend-tmp;12                  tmp<<=1;13                  14                  if(tmp>dividend){15                        break;16                  }17                  18                  else{19                        result<<=1;20                  }21           }22           23           return result+interDivide(left,divisor);24     }25     26     int Divide(int dividend,int divisor){27           unsigned long long _dividend=abs((long long)dividend);28           unsigned long long _divisor=abs((long long)divisor);29           30           bool positive=((dividend>=0) && (divisor>0)) || ((dividend<=0) && (divisor<0));31           32           return positive?interDivide(_dividend,_divisor):(-1)*interDivide(_dividend,_divisor);33           34     }35 };

Unsigned long is used to prevent overflow.

 

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