Leetcode: divide two integers solution report

Source: Internet
Author: User

Divide two integers


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

Solution 1
1. The basic idea is to constantly reduce the divisor until it is 0. But it will be too slow.

2. We can use a two-way method to accelerate this process. Continue to divisor * 2 until it is bigger than the divisor. At the same time, the CNT is also recorded, and the value after the divisor is reduced and the result is + CNT.

Because it is doubled, the speed will be very fast and exponential.

3. In addition, it should be noted that the minimum value is out of the border. Take ABS for the smallest positive number and get it... Because the absolute value of the smallest positive number is greater than the largest positive number (INT)

So we can use long to catch this set.

1 public class solution {2 Public int divide (INT dividend, int divisor) {3 long a = math. ABS (long) dividend); 4 5 // Ref: http://blog.csdn.net/kenden23/article/details/16986763 6 // Note: here you must take long and then abs, otherwise, the minimum value of Int Is abs and the original value is 7 long B = math. ABS (long) divisor); 8 9 int ret = 0; 10 // Here it must be = because when it is equal, it can also be reduced by 11 while (A> = B) {12 // The Judgment condition is> = 13 for (long deduce = B, CNT = 1; A >= deduce; deduce <= 1, CNT <= 1) {14 A-= deduce; 15 RET + = CNT; 16} 17} 18 19 // get the symbol bit. 20 return (dividend> 0) ^ (divisor> 0 )? -RET: ret; 21} 22}
View code

GitHub code:

Divide. Java

 

Ref: http://blog.csdn.net/fightforyourdream/article/details/16899675

Leetcode: divide two integers solution report

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.