My simple recursion solution


  • 2
    I
    class Solution {
    public:
    int divide(long long dividend, long long divisor) {                                                                               
        int exp2 = 0;
        long long ret;
        long long p = abs(dividend), q = abs(divisor);
        if(p < q)     //递归出口
            return 0;
    
        while(p - q >= 0){
            p -=  q;
            q = q + q;
            exp2++;
        }
        ret = divide(p, abs(divisor));    //figure out new_p
        ret += (0x1 << exp2) - 1;
        if(dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0)
            ret = -ret;
        if(ret >= (unsigned int)(0x1<<31)) --ret;
        return ret;
    }
    

    };

    My idea is this equation: p=q(1+2+4+...+2^(exp-1))+new_p, and new_p is figured by recursion.


  • 0
    M
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.