166. Fraction to Recurring Decimal #2210
-
Topics: Given two integers representing the If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to convert a fraction into its string representation, handling repeating decimals by enclosing the repeating part in parentheses. The solution involves simulating the long division process while keeping track of remainders to detect cycles. Approach
Let's implement this solution in PHP: 166. Fraction to Recurring Decimal <?php
/**
* @param Integer $numerator
* @param Integer $denominator
* @return String
*/
function fractionToDecimal($numerator, $denominator) {
if ($numerator == 0) {
return "0";
}
$sign = "";
if (($numerator < 0) ^ ($denominator < 0)) {
$sign = "-";
}
$numerator = abs($numerator);
$denominator = abs($denominator);
$integerPart = intval($numerator / $denominator);
$remainder = $numerator % $denominator;
if ($remainder == 0) {
return $sign . $integerPart;
}
$fractionalPart = "";
$remainderMap = [];
while ($remainder != 0) {
if (isset($remainderMap[$remainder])) {
$startIndex = $remainderMap[$remainder];
$fractionalPart = substr($fractionalPart, 0, $startIndex) . '(' . substr($fractionalPart, $startIndex) . ')';
break;
}
$remainderMap[$remainder] = strlen($fractionalPart);
$remainder *= 10;
$fractionalPart .= intval($remainder / $denominator);
$remainder %= $denominator;
}
return $sign . $integerPart . '.' . $fractionalPart;
}
// Test cases
echo fractionToDecimal(1, 2) . "\n"; // "0.5"
echo fractionToDecimal(2, 1) . "\n"; // "2"
echo fractionToDecimal(4, 333) . "\n"; // "0.(012)"
echo fractionToDecimal(1, 6) . "\n"; // "0.1(6)"
echo fractionToDecimal(-50, 8) . "\n"; // "-6.25"
echo fractionToDecimal(7, -12) . "\n"; // "-0.58(3)"
?> Explanation:
This approach efficiently handles both non-repeating and repeating decimals by leveraging the properties of long division and cycle detection using a hash map. The solution ensures that all edge cases, including negative numbers and zero, are handled correctly. |
Beta Was this translation helpful? Give feedback.
We need to convert a fraction into its string representation, handling repeating decimals by enclosing the repeating part in parentheses. The solution involves simulating the long division process while keeping track of remainders to detect cycles.
Approach