原题链接在这里:
题目:
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
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)".
题解:
加入整数部分后,在reminder 不为0的时候添加小数部分,用HashMap来维护reminder 和 对应的小数长度. 若是出现无限循环可以找到加左括号的起始点.
AC Java:
1 public class Solution { 2 public String fractionToDecimal(int numerator, int denominator) { 3 if(numerator == 0){ 4 return "0"; 5 } 6 if(denominator == 0){ 7 return ""; 8 } 9 10 StringBuilder res = new StringBuilder();11 long num = Math.abs((long)numerator);12 long deno = Math.abs((long)denominator);13 14 //如果是负数15 if((numerator < 0) ^ (denominator < 0)){16 res.append("-");17 }18 19 res.append(num/deno);20 long reminder = num%deno;21 if(reminder == 0){22 return res.toString();23 }24 25 //有小数26 res.append(".");27 //HashMap中计入reminder 和 对应的小数部分长度,用来找到循环开始的位置28 HashMaphm = new HashMap ();29 StringBuilder desRes = new StringBuilder();30 while(reminder != 0){31 if(hm.containsKey(reminder)){ //出现了循环,找到循环开始的index添加左括号32 int beginIndex = hm.get(reminder);33 desRes.insert(beginIndex, "(");34 desRes.append(")");35 res.append(desRes);36 return res.toString();37 }38 hm.put(reminder, desRes.length());39 desRes.append(reminder*10/deno);40 reminder = (reminder*10)%deno;41 }42 res.append(desRes);43 return res.toString();44 }45 }
与类似.