@mzchen's solution javscripted


  • 0
    E
    var fractionToDecimal = function(n, d) {
        if (n === 0) return '0';
        
        var res = '';
        
        if (n < 0 ^ d < 0) res += '-';
        
        n = Math.abs(n);
        d = Math.abs(d);
        
        res += Math.floor(n/d);
        
        if (n % d === 0) return res;
        
        res += '.';
        
        var lookup = {};
        for (var r = n % d; r !== 0; r %= d)
        {
        	// test whether this remainder has been seen
        	if (lookup[r] !== undefined)
        	{
        		return res.slice(0, lookup[r]) + '(' + res.slice(lookup[r]) + ')';
        	}
        	
        	lookup[r] = res.length;
        	r *= 10;
        	res += Math.floor(r / d);
        }
        return res;
    };
    

Log in to reply
 

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