Divide two integers without using multiplication, division and mod operator.
Analysis:
As multiplication and division operations are forbade, we could using deduction - deduct divisor from dividend until the remainder is less than the divisor, and count how many times we performed the deduction. However, the algorithm yields TLE.
The idea is that instead of deducting the divisor from dividend, we deduct i*divisor from the dividend. We repeatedly increase i to reduce the number of deductions, until the remainder is less that i*divisor.
Takeaway:
abs(INT_MIN) or -INT_MIN doesn't produce positive result. We could choose one of the following approaches:
long long pos1 = abs((double) INT_MIN); unsigned int pos2 = -INT_MIN; // or abs(INT_MIN)Code:
class Solution {
public: int divide(int dividend, int divisor) { if (dividend==0 || divisor==0) return 0; int sign=(dividend^divisor)>>31; long long rem=abs((double)dividend); long long div=abs((double)divisor); long long res=0; while(rem>=div && rem>0) { long long div2=div; for (int i=0; rem>=div2; i++, div2<<=1) { rem-=div2; res+=1<<i; } } return sign==0? res:-res; } };
No comments:
Post a Comment