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)".
T:
Keep a remainder. Multiply it by 10 each time we append a new digit to the result, and append the quotient as the new digit, and assign remainder as the mod of the remainder to the denominator. We need a hashmap to store the positions of each remainder. When we see a remainder again, we know the digits will cycle.
A:
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
int sign = 0;
if((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0)) {
sign = 1;
}
int64_t n = numerator;
int64_t d = denominator;
n = abs(n);
d = abs(d);
string ret = "";
if(sign) {
ret += "-";
}
ret += to_string(n/d);
if(n%d == 0) {
return ret;
}
ret += ".";
unordered_map< int, int > mark;
int64_t r = n%d;
while(r > 0) {
if(mark[r] > 0) {
ret.insert(mark[r], 1, '(');
ret += ")";
return ret;
}
mark[r] = ret.size();
r *= 10;
ret += to_string(r/d);
r %= d;
}
return ret;
}
};
No comments:
Post a Comment