"Leetcode" P029_dividetwointegers

Source: Internet
Author: User

Topic

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

If It is overflow, return max_int.

The title means: Do not use the *,/,% operator for division operations

Ideas

The most direct idea of the problem is that the divisor is subtracted every time, the calculation is reduced by how many times, that is, the request. But the efficiency of this approach is too low, imagine dividend is Integer.max_value (2147483647), the divisor is 1, then 2,147,483,647 times, it will obviously happen tle.

A better approach:
Instead of subtracting the divisor each time, the divisor is incremented each time, resulting in a corresponding multiple of the divisor.

Code
  
 
  1. public class P029_DivideTwoIntegers {
  2. public int divide(int dividend, int divisor) {
  3. int sign = 1;
  4. if (dividend < 0) {
  5. sign = -sign;
  6. }
  7. if (divisor < 0) {
  8. sign = -sign;
  9. }
  10. long n1 = Math.abs((long)dividend);
  11. long n2 = Math.abs((long)divisor);
  12. long ans = 0;//用long是为了处理溢出,比如当ans为2147483648的情况
  13. while (n1 >= n2) {
  14. long base = n2;
  15. for (int i = 0; n1 >= base; i++) {
  16. n1 -= base;
  17. base<<=1;
  18. ans+=1<<i;
  19. }
  20. }
  21. //处理溢出的情况
  22. //int的范围为-2147483648到2147483647
  23. //dividend=Integer.MIN_VALUE,即-2147483648
  24. //divisor=-1,此时将发生溢出,按题目要求,返回Integer.MAX_VALUE
  25. if (ans * sign > Integer.MAX_VALUE)
  26. return Integer.MAX_VALUE;
  27. return (int) (sign*ans);
  28. }
  29. }


From for notes (Wiz)

"Leetcode" P029_dividetwointegers

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.