Title Description:
Given integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part was 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) ".
is to give a divisor and dividend a string expression that returns a decimal. Requirements: For Infinite loop decimals, the brackets are marked to follow the link.
Ideas:
This is a math problem. First of all to clarify a point, but also the premise of the topic, any score does not exist infinite non-cyclical decimals.
So you can keep using the numerator n divided by the denominator D to record the result.
If you can return the results directly, except as possible.
Otherwise, when the hash table is used to save the remainder and the last occurrence, you can add parentheses to return the results.
Implementation code:
public class Solution {public string fractiontodecimal (int numerator, int denominator) {if (numerator = = 0) return "0"; if (denominator = = 0) return ""; var result = ""; is result is negativeif ((Numerator < 0) ^ (Denominator < 0)) {result + = "-";}//convert int to Longlong num = n Umerator, den = Denominator;num = Math.Abs (num);d en = Math.Abs (DEN); Quotient long res = Num/den;result + = Res. ToString (); If remainder is 0, return resultlong remainder = (num% den) * 10;if (remainder = = 0) return result; Right-hand side of decimal pointdictionary<long, int> map = new Dictionary<long, int> (); result + = "."; while (remainder! = 0) {//If digits repeatif (map. ContainsKey (remainder)) {int beg = Map[remainder]; var part1 = result. Substring (0, beg); var part2 = result. Substring (Beg, result. Length-beg); result = Part1 + "(" + Part2 + ")"; return result; Continuemap. ADD (remainder, result. res = Remainder/den;result + = Res. ToString (); remainder = (remainDer% den) * 10;} return result; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Fraction to recurring Decimal