http://www.lintcode.com/zh-cn/problem/add-operators/
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)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(numerator==0) return "0";
if(denominator==0) return "";
long a = numerator, b = denominator;
a = Math.abs(a);
b = Math.abs(b);
// //直接转abs会溢出
// long a = Math.abs(numerator);
// long b = Math.abs(denominator);
StringBuffer res = new StringBuffer("");
if ((numerator < 0) ^ (denominator < 0)){
res.append("-");
}
long pre = a/b;
res.append(pre);
long rem = (a%b)*10;
if(rem==0) return res.toString();
Map<Long, Integer> map = new HashMap<Long, Integer>();
res.append(".");
while(rem!=0){
//已经出现过该余数,最后的过程相同可定得到相同的循环
if(map.containsKey(rem)){
int bei = map.get(rem);
return res.substring(0, bei)+"("+res.substring(bei, res.length())+")";
}
//没有出现过该余数
map.put(rem, res.length());
pre = rem/b;
res.append(pre);
rem = (rem%b)*10;
}
return res.toString();
}
}