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)".
class Solution {
public:
string getFraction(long long numerator, long long denominator) {
string fraction = ".";
numerator *= 10;
map<long long, int> mp;
int pos = 1;
while (numerator != 0) {
if (mp.find(numerator) != mp.end()) {
fraction.insert(mp[numerator], 1, '(');
fraction.push_back(')');
return fraction;
} else {
mp[numerator] = pos;
}
fraction += to_string(numerator / denominator);
numerator = 10 * (numerator % denominator);
pos++;
}
return fraction;
}
string fractionToDecimal(int num, int den) {
string ans; bool sign = false;
if (den == 0 || num == 0) {
return "0";
}
if ((den < 0 && num < 0) ||
(den > 0 && num > 0)) {
sign = true;
}
long long numerator = abs((long long) num);
long long denominator = abs((long long) den);
ans += to_string(numerator / denominator);
if (numerator % denominator != 0) {
ans += getFraction(numerator % denominator, denominator);
}
return (sign == false ? "-" + ans : ans);
}
};
========
string fractionToDecimal(int numerator, int denominator) { int s1 = numerator >= 0 ? 1 : -1; int s2 = denominator >= 0 ? 1 : -1; long long num = abs( (long long)numerator ); long long den = abs( (long long)denominator ); long long out = num / den; long long rem = num % den; unordered_map<long long, int> m; string res = to_string(out); if (s1 * s2 == -1 && (out > 0 || rem > 0)) res = "-" + res; if (rem == 0) return res; res += "."; string s = ""; int pos = 0; while (rem != 0) { if (m.find(rem) != m.end()) { s.insert(m[rem], "("); s += ")"; return res + s; } m[rem] = pos; s += to_string((rem * 10) / den); rem = (rem * 10) % den; ++pos; } return res + s; }
==========
class Solution {
public:
string fractionToDecimal(int num, int denom) {
int sign_a = (num < 0 ? -1 : 1);
int sign_b = (denom < 0 ? -1 : 1);
string ans;
if (denom == 0 || num == 0) {
return "0";
}
long numerator = labs(num);
long denominator = labs(denom);
if (sign_a * sign_b == -1) {
ans += "-";
}
long remaining = numerator % denominator;
ans += to_string(numerator/denominator);
if (remaining == 0) {
return ans;
} else {
ans += ".";
}
// Prepare the fraction.
map<long, long> mp;
while (1) {
if (mp.count(remaining) != 0) {
string tmp = ans.substr(mp[remaining]); // 6
string pre = ans.substr(0, mp[remaining]); // 0.
return pre + "(" + tmp + ")";
}
if (remaining == 0) {
return ans;
}
mp[remaining] = ans.size(); // mp[4] = 2
int count = 0;
while (remaining < denominator) {
remaining *= 10;
count++;
}
while (count > 1) {
ans += "0";
count--;
}
ans += to_string(remaining/denominator); // 0.6
remaining = remaining % denominator;
}
return ans;
}
};
No comments:
Post a Comment