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)".
public class Solution { public String fractionToDecimal(int numerator, int denominator) { //注意正负 //注意越界(转为long) //使用map记录余数和位置,当发现相同的余数时,则表示此余数对应位置的商位开始循环,此时需要用()包装 //seq表示商 long num=Math.abs((long)numerator); long deno=Math.abs((long)denominator); int flag=1; if(numerator>0&&denominator<0||numerator<0&&denominator>0) flag=0; long s=num/deno; long t=num%deno; String res=flag==0?"-"+Long.toString(s):Long.toString(s); if(t==0) return res; else return res+"."+getRes(t,deno); } public StringBuilder getRes(long t,long deno){ StringBuilder seq=new StringBuilder(); HashMap<Long,Integer> map=new HashMap<Long,Integer>(); int i=0; while(t!=0&&!map.containsKey(t)){ map.put(t,i); i++; t*=10; seq.append(Long.toString(t/deno)); t%=deno; } if(t!=0){ seq.insert((int)map.get(t),‘(‘); seq.append(‘)‘); } return seq; } }
时间: 2024-11-09 06:20:39