问题描述,输入两个整数a, b,将分数输出a/b的小数格式,如果a/b是循环小数,则将循环部分用括号括起来,例如:
1/4 = 0.25; 1/3=0.(3); 1/6=0.1(6);
分析:实质上是实现高精度浮点数除法。借助哈希表来获取循环部分。
public class Solution {
static int b = Integer.SIZE - 1;
public static String fractionToDecimal(int numerator, int denominator) {
StringBuffer res = new StringBuffer();
long remainder = numerator;
long der = denominator;
if(remainder*der<0) res.append('-');
remainder = Math.abs(remainder);
der = Math.abs(der);
res.append(remainder/der); //整数部分
remainder%=der; remainder*=10;
if(remainder==0) return res.toString();
else{
res.append('.');
//缓存表,用于搜寻循环位
HashMap<Long,Integer> tab = new HashMap<Long,Integer>();
while(!tab.containsKey(remainder) && remainder>0){
while(remainder<der){
tab.put(remainder, res.length());
res.append('0'); remainder*=10;
}
tab.put(remainder, res.length());
res.append(remainder/der);
remainder%=der; remainder*=10;
}
if(remainder==0) return res.toString(); //有限小数
else{
res.insert(tab.get(remainder), "(");
res.append(")");
}
}
return res.toString();
}