题目
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.
答案
class Solution {
public String fractionToDecimal(int n, int d) {
Map<Long, Integer> map = new HashMap<>();
if(n == 0) return "0";
String sign = ((n > 0) ^ (d > 0)) ? "-":"";
String ans = "";
long numerator = n, denominator = d;
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
// Calculate integer part
long integer_part = numerator / denominator;
ans = ans + Long.toString(integer_part);
// Check if fractional part exists
if(numerator % denominator != 0)
ans = ans + ".";
else
return sign + ans;
// Calculate fractional part
for(long r = numerator % denominator; r != 0; r = r % denominator) {
Integer lookup = map.get(r);
if(lookup != null) {
String part1 = ans.substring(0, lookup);
String part2 = ans.substring(lookup, ans.length());
ans = part1 + "(" + part2 + ")";
break;
}
map.put(r, ans.length());
r = r * 10;
ans = ans + Long.toString(r / denominator);
}
return sign + ans;
}
}
网友评论