class Solution {
public String fractionToDecimal(int numerator, int denominator) {
long a=numerator,b=denominator;
StringBuffer sb=new StringBuffer();
if(a%b==0)
return String.valueOf(a/b);
if((a<0&&b>0)||(a>0&&b<0)){
sb.append("-");
}
a=Math.abs(a);
b=Math.abs(b);
sb.append(a/b+".");
a=a%b;
HashMap<Long,Integer> map=new HashMap<>();
map.put(a,sb.length());
while(a!=0){
map.put(a,sb.length());//记录上一次的余数
a=a*10;
long tmp=a/b;//上的位
sb.append(tmp);
a=a%b;//这次的余数
//前面已经出现过这个余数
if(map.containsKey(a)){
int index=map.get(a);
return String.format("%s(%s)", sb.substring(0, index), sb.substring(index));
}
}
return sb.toString();
}
}
每日一题 LeetCode 166. 分数到小数 java
最新推荐文章于 2022-03-24 12:07:20 发布