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

If it is overflow, return2147483647

Have you met this question in a real interview?

Yes

Example

Given dividend =100and divisor =9, return11.

line 10 cast to long

line 14

<

<

=

line 20 add sign first , then check with INT32_MAX

class Solution {

public:

/\*\*

 \* @param dividend the dividend

 \* @param divisor the divisor

 \* @return the result

 \*/

int divide\(int dividend, int divisor\) {

    // Write your code here

    long a = abs\(\(long\)dividend\), b = abs\(\(long\)divisor\);



    long res = 0;

    while \(a &gt;= b\) {

        for \(long count = 1, tmp = b; a &gt;= tmp; tmp &lt;&lt;= 1, count &lt;&lt;= 1\) {

            res += count;

            a -= tmp;

        }

    }



    res = \(\(dividend ^ divisor\) &gt;&gt; 31\) ? -res : res;

    if \(res &gt; INT32\_MAX\)

        return INT32\_MAX;

    return res;

}

};

results matching ""

    No results matching ""