Java [Leetcode 29]divide-integers

Source: Internet
Author: User

Title Description:

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

If It is overflow, return max_int.

Problem Solving Ideas:

The divisor is expressed as: dividend = 2^i * divisor + 2^ (i-1) * divisor + ... + 2^0 * divisor. In this way, the quotient we seek is the sum of the coefficients, and each coefficient can be obtained by means of a shift operation.

For detailed explanation, please refer to: http://blog.csdn.net/whuwangyi/article/details/40995863

The code is as follows:

public class Solution {public    int divide (int dividend, int divisor) {Boolean flag = (Dividend > 0 && Divis or > 0) | |  (Dividend < 0 && Divisor < 0); long absdividend = Math.Abs ((long) dividend); Long absdivisor = Math.Abs ((long) divisor); Long quotient = Dividepositive (Absdividend, absdivisor); if (flag && quotient > Integer.max_value) Return Integer.max_value;return flag? (int) Quotient:-(int) quotient;} Public long dividepositive (long dividend, long divisor) {if (Dividend < divisor) return 0;long quotient = 1;long Origina Ldivisor = Divisor;while (Dividend >= (divisor << 1)) {quotient <<= 1;divisor <<= 1;} Return quotient + dividepositive (dividend-divisor, originaldivisor);}}

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