Beat 98% Fast Java Solution using Long type


  • 0
    M
     public String fractionToDecimal(int n, int d) {
        StringBuilder sb = new StringBuilder();
    	long numerator = n, denominator = d;
    	boolean isNegative = false;
    	if (numerator < 0) {
    		numerator = -numerator;
    		isNegative = !isNegative;
    	}
    	if (denominator < 0) {
    		denominator = -denominator;
    		isNegative = !isNegative;
    	}
    
    	long quotient = numerator / denominator;
    	long remain = numerator - denominator * quotient;
    
    
    	if (isNegative && numerator !=0)
    		sb.append('-');
    	sb.append(quotient);
    	if (remain != 0) {
    		sb.append('.');
    		HashMap<Long, Integer> map = new HashMap<Long, Integer>();
    		while (remain != 0 ) {
    			if (!map.containsKey(remain)) {
    				map.put(remain, sb.length());
    				numerator = remain * 10;
    				quotient = numerator / denominator;
    				sb.append(quotient);
    				remain = numerator % denominator;
    			} else {
    				sb.insert((int) map.get(remain), '(');
    				sb.append(')');
    				break;
    			}
    		}
    	}
    
    	return sb.toString();
    
    }

  • 0
    O

    My solution is very similar with yours but it does run slower, could you tell me why?

       public String fractionToDecimal(int numerator, int denominator) {
        	
        	if (numerator % denominator == 0)
        		return ((long)numerator / denominator) + "";
        	
        	Map<Long, Integer> map = new HashMap<Long, Integer>();
        	StringBuilder ans = new StringBuilder((numerator < 0 ^ denominator < 0) ? "-" : "");
        	ans.append(Math.abs(numerator / denominator)).append(".");
        	long dtr = denominator < 0 ? (long)denominator * -1 : denominator;
        	long mod = (numerator < 0 ? (long)numerator * -1 : numerator) % dtr;
        	
        	while (mod != 0) {
            	if (map.containsKey(mod))
            		return ans.insert(map.get(mod), "(").append(')').toString();
            	map.put(mod, ans.length());
        		ans.append(mod * 10 / dtr);
        		mod = mod * 10 % dtr;
        	}
        return ans.toString();
    }

Log in to reply
 

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