Java - looks short, it is actually pretty tricky to make it pass.


  • 0
    J
    public class Solution {
    public static void main (String[] args) {
    	Solution sol = new Solution();
    	sol.fractionToDecimal(-1,  -2147483648);
    }
    public String fractionToDecimal(int numerator, int denominator) {
    	StringBuffer ans = new StringBuffer();
    	Map<Long, Integer> map = new HashMap<>();
    	String sign;
    	if ((numerator == 0 ) || (numerator >= 0 && denominator > 0 ) 
    			|| (numerator < 0 && denominator < 0)) {
    		sign = "";
    	} else {
    		sign = "-";
    	}
    	ans.append(sign);
    	long lnumerator = Math.abs((long) numerator);
    	long ldenominator = Math.abs((long ) denominator);
    	
     	ans.append(lnumerator / ldenominator);
    	long r = lnumerator % ldenominator;
    	if (r > 0) {
    		ans.append(".");
    	} else {
    		return ans.toString();
    	}
    	
    	while (!map.containsKey(r) && r > 0) {
    		map.put(r, ans.length());
    		ans.append(10 * r / ldenominator);
    		r = (10 * r % ldenominator);
     	} 
    	if (r > 0) {
    		long len = map.get(r);
    		ans.insert((int) len, "(");
    		ans.append(")");
    	}
    	
    	return ans.toString();
        
    }
    

    }


  • 0
    T

    Mean little problem, like Integer.parseInt(String,int)'s implementation.


Log in to reply
 

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