If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
- Given numerator = 1, denominator = 2, return "0.5".
- Given numerator = 2, denominator = 1, return "2".
- Given numerator = 2, denominator = 3, return "0.(6)".
public class Solution { public String fractionToDecimal(int numerator, int denominator) { // http://blog.csdn.net/ljiabin/article/details/42025037 if (numerator == 0) return "0"; if (denominator == 0) return ""; String ans = ""; // If different signs if ((numerator < 0) ^ (denominator < 0)) ans += "-"; // Converto to 'long' type in case of overflow long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); // Get integer quotient long res = num/den; ans += String.valueOf(res); // (Remainder*10) / denominator in case of integer division long rem = (num % den) * 10; // Check if there is remainder if (rem == 0) return ans; // Fractional part --- <Remainder, Index> HashMap<Long, Integer> map = new HashMap<>(); ans += "."; while (rem != 0) { // If this remainder has already appeared, it indicates loop. if (map.containsKey(rem)) { // Obtain index of loop remainder int id = map.get(rem); String nonLoop = ans.substring(0, id); String loop = ans.substring(id, ans.length()); ans = nonLoop + "(" + loop + ")"; return ans; } // Continue division map.put(rem, ans.length()); res = rem / den; ans += String.valueOf(res); rem = (rem % den) * 10; } return ans; } }
No comments:
Post a Comment