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)".
由于兩個整數(shù)相除會出現(xiàn)一串重復(fù)出現(xiàn)的數(shù)字面殖,例如1/7 = 0.(142857)
如果此時的numerator =1, 把此時的字符串0.長度2插入旁钧,如果再出現(xiàn)1遭居,那么表示后面的都是重復(fù),用括號把2之后的都括起來就行。
于是:
1-2,3-3恤筛,2-4,6-5芹橡,4-6毒坛, 然后又變成1
- 注意:將int都轉(zhuǎn)為long, 不然在取絕對值的時候會出錯。
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(numerator == 0) return "0";
StringBuilder res = new StringBuilder();
if((numerator>0) ^ (denominator>0)) res.append("-");
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
//integer part
res.append(num/den);
num %= den;
if(num == 0) return res.toString();
//fractional part
res.append(".");
Map<Long, Integer> map = new HashMap<>();
map.put(num, res.length());
while(num!=0){
num *= 10;
res.append(num/den);
num %= den;
if(map.containsKey(num)){
int index = map.get(num);
res.insert(index, "(");
res.append(")");
break;
}
else{
map.put(num, res.length());
}
}
return res.toString();
}
}