JAVA--------------Easy Version To Understand!!!


  • 0
    H
    	public static String fractionToDecimal(int numerator, int denominator) {
    	if (numerator == 0)
    		return "0";
    	if (denominator == 0)
    		return null;
    	StringBuffer result = new StringBuffer(); 
    	if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0))
    		result.append("-");
    	long Numerator = Math.abs((long) numerator);
    	long Denominator = Math.abs((long) denominator);
    	result.append(String.valueOf(Numerator / Denominator));
    	long remainder;
    	int position = 0, recurFrom, recurTo, flag = 0;
    	StringBuffer s = new StringBuffer();
    	HashMap<Long, Integer> map = new HashMap<Long, Integer>();
    	if (Numerator % Denominator != 0) 
    		remainder = Numerator % Denominator;
    		while (remainder != 0) {
    			map.put(remainder, position);
    			long tmp = remainder * 10;
    			s.append(String.valueOf(tmp / Denominator));
    			remainder = tmp % Denominator;
    			if (map.get(remainder) != null) {
    				recurFrom = map.get(remainder);
    				recurTo = position + 1;
    				result.append('.');
    				result.append(s.subSequence(0, recurFrom));
    				result.append('(');
    				result.append(s.subSequence(recurFrom, recurTo));
    				result.append(')');
    				return result.toString();
    			}
    			position++;
    		}
    		result.append(".");
    		result.append(s);
    	}
    	return result.toString();
    }

Log in to reply
 

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