166.分数到小数 class Solution {public String fractionToDecimal(int numerator, int denominator) {StringBuilder sb = new StringBuilder();HashMap<Long,Integer> map = new HashMap<>();//为了防止溢出,将分子和分母都转成64位整数long a = numerator,b = denominator;if(a * b < 0){sb.append('-');}a = Math.abs(a);b = Math.abs(b);sb.append(a / b);if(a % b == 0){return sb.toString();}sb.append('.');//计算小数部分, 每次将余数乘以10,然后计算小数的下一位数字,得到新的余数while((a = (a % b) * 10) > 0 && !map.containsKey(a)){map.put(a,sb.length());sb.append(a/b);}if(a==0){ //有限小数return sb.toString();}//无限小数,找到循环开始的位置,即之前出现过的余数,通过哈希表得到return sb.insert(map.get(a).intValue(),'(').append(')').toString();} }