Java solution O(log dividend/log divisor)


  • 0

    Just for reference. If there is mistake about time complexity, it would be great if you could write down your analysis of the program. ;)

    public int divide(int dividend, int divisor) {
            int a = 0;
            long ans = 0;
            long dd =  Math.abs((long)dividend);
            long ds =  Math.abs((long)divisor);
            int cur = 1;
            long tds = ds;
            while(dd>0){
                dd -= tds;
                if(dd<0){
                    if(cur == 1) break;
                    dd += tds;
                    tds = ds;
                    cur = 1;
                    continue;
                }
                ans += cur;
                tds += tds;
                cur += cur;
    
            }
            ans = (dividend>0&&divisor>0)||(dividend<0&&divisor<0)?ans:-ans;
            if(ans>Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if(ans<Integer.MIN_VALUE) return Integer.MIN_VALUE;
            return (int) ans;
        }
    

Log in to reply
 

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