Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.app
If the fractional part is repeating, enclose the repeating part in parentheses.ui
Example 1:code
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:orm
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:ci
Input: numerator = 2, denominator = 3
Output: "0.(6)"rem
邏輯性很強的題目
若是不轉換爲long去計算:get
Input: -1 -2147483648 Output: "0.0000000000000000000000000000001" Expected: "0.0000000004656612873077392578125"
class Solution { public String fractionToDecimal(int numerator, int denominator) { StringBuilder sb = new StringBuilder(); //get sign String sign = numerator < 0 == denominator < 0 || numerator == 0 ? "" : "-"; //get integer part long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); sb.append(sign).append(num/den); //if remainder is 0 long rmd = num%den; if (rmd == 0) return sb.toString(); //if remainder not 0, //get decimal parts sb.append("."); //use map to record repeating fractional part //update map, remainder and res string until found repeating part Map<Long, Integer> map = new HashMap<>(); while (!map.containsKey(rmd)) { map.put(rmd, sb.length()); sb.append(10*rmd/den); rmd = 10*rmd%den; } //deal with repeating part int index = map.get(rmd); sb.insert(index, "("); sb.append(")"); //return res and exclude (0) case return sb.toString().replace("(0)", ""); } }