Fraction to Recurring Decimal
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)".
--------------------------------------------------- thinking --------------------------------------------------------------------
This problem should use hash table to record if a numerator has been repeating or not. Remember the interface of unordered_map<int, int>. And the hash key should be the numerator, while the value should be the position of current numerator!
-------------------------------------------------- problems ------------------------------------------------------------------
the overflow problem should be considered here!!! the plus-minus sign should also be considered here!! So it's very important to change the type from "int" to "long"
---------------------------------------------- codes --------------------------------------------------------------------------
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string result = "";
if (numerator == 0) {
return "0";
}
//calc symble
if ((numerator<0)^(denominator<0)) {
result += "-";
}
long n = abs(long(numerator));
long d = abs(long(denominator));
long r = n / d;
result += to_string(r);
if (n%d == 0) {
return result;
}
result += ".";
unordered_map<int, int> map;
r = n % d;
while (r) {
if (map.count(r) > 0) {
result.insert(map[r], 1, '(');
result += ')';
return result;
}
map[r] = result.size();
r *= 10;
long cur = r / d;
result += to_string(cur);
r = r % d;
}
return result;
}
};
No comments:
Post a Comment