Leetcode 166. Fraction to Recurring Decimal
Given two integers representing the numerator and the denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses.
Q: What kind of inputs can I expect for the numerator and denominator?
A: The numerator and denominator will always be integers, and the denominator will not be zero.
Q: Can the fraction be negative?
A: Yes, either numerator or denominator or both can be negative.
Q: What should I return if the result is a whole number?
A: You should return the whole number without any decimal point.
Here’s a C++ implementation of the strategy:
#include <iostream>
#include <string>
#include <unordered_map>
#include <cmath>
using namespace std;
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
string result;
// Handle negative numbers
if ((numerator < 0) ^ (denominator < 0)) result += "-";
// Convert to long to prevent overflow
long long n = abs((long long)numerator);
long long d = abs((long long)denominator);
// Adding the integer part
result += to_string(n / d);
long long remainder = n % d;
if (remainder == 0) return result;
result += ".";
unordered_map<long long, int> remainderPositions;
while (remainder != 0) {
if (remainderPositions.find(remainder) != remainderPositions.end()) {
result.insert(remainderPositions[remainder], "(");
result += ")";
break;
}
remainderPositions[remainder] = result.size();
remainder *= 10;
result += to_string(remainder / d);
remainder %= d;
}
return result;
}
int main() {
// Example test cases
cout << fractionToDecimal(1, 2) << endl; // Output: "0.5"
cout << fractionToDecimal(2, 1) << endl; // Output: "2"
cout << fractionToDecimal(2, 3) << endl; // Output: "0.(6)"
cout << fractionToDecimal(4, 333) << endl; // Output: "0.(012)"
return 0;
}
The overall time complexity is O(d), where d is the value of the denominator.
This approach ensures that we handle all required edge cases, including negative numbers, whole numbers, and both terminating and repeating decimals.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?