LeetCode刷题实战166:分数到小数
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
题意
104
。示例 1:
输入:numerator = 1, denominator = 2
输出:"0.5"
示例 2:
输入:numerator = 2, denominator = 1
输出:"2"
示例 3:
输入:numerator = 2, denominator = 3
输出:"0.(6)"
示例 4:
输入:numerator = 4, denominator = 333
输出:"0.(012)"
示例 5:
输入:numerator = 1, denominator = 5
输出:"0.2"
解题
思路:
public static String fractionToDecimal(int numerator, int denominator) {
//特殊情况单独处理
if(numerator==0) {
return "0";
}
//符号位单独判断-1为负,0为正
int flag = (numerator^denominator)>>31;
//整数部分的值单独求
long num = Math.abs((long)numerator),den = Math.abs((long)denominator);
long Int = num/den;
long remainder = num%den;
StringBuffer res = new StringBuffer();
res.append(flag==-1?"-"+Int:Int);
if(remainder==0) {
//可以整除
return res.toString();
}
//不能整除,先加一个小数点
res.append(".");
//小数部分单独处理,有能除尽和循环两种情况
//是否循环通过Map对应位置来判断
//出现循环应当是余数出现和之前相同了
Mapmap = new LinkedHashMap ();
long div = 0;
while(remainder!=0) {
remainder *= 10;
//获取商
div = remainder/den;
map.put(remainder/10,div); //将余数和商存入
remainder %= den;
if(map.containsKey(remainder)) {
//出现循环了,将所有循环数括起来
//注意此处应当是从循环的位置括起来,而不是开头
int fla = 0;
for(Long key:map.keySet()) {
if(fla==0&&key!=remainder) {
res.append(map.get(key));
}
if(key==remainder) {
fla = 1;res.append("(");
}
if(fla==1) {
res.append(map.get(key));
}
}
res.append(")");
return res.toString();
}
}
for(Long key:map.keySet()) {
res.append(map.get(key));
}
return res.toString();
}