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.
Example 1:
Input:numerator = 1, denominator = 2Output: "0.5"
Example 2:
Input:numerator = 2, denominator = 1Output: "2"
Example 3:
Input:numerator = 2, denominator = 3Output: "0. (6) "
Gives 2 integers as numerator and denominator, returning the string form of a fraction.
Java:
public class Solution {public String fractiontodecimal (int numerator, int denominator) {if (numerator = = 0) { return "0"; } StringBuilder res = new StringBuilder (); "+" or "-" Res.append (((Numerator > 0) ^ (Denominator > 0))? "-" : ""); Long num = Math.Abs ((long) numerator); Long den = Math.Abs ((long) denominator); Integral part res.append (Num/den); Num%= den; if (num = = 0) {return res.tostring (); }//Fractional part res.append ("."); Hashmap<long, integer> map = new Hashmap<long, integer> (); Map.put (num, res.length ()); while (num! = 0) {num *= 10; Res.append (Num/den); Num%= den; if (Map.containskey (num)) {int index = map.get (num); Res.insert (Index, "("); Res.append (")"); Break } else {map.put (num, res.length ()); }} return res.tostring (); }}
Python:
Class solution (Object): def fractiontodecimal (self, numerator, denominator): "" " : Type Numerator:int : Type Denominator:int : Rtype:str "" " result =" " if (Numerator > 0 and Denominator < 0) or (n Umerator < 0 and denominator > 0): result = "-" DVD, DVS = ABS (numerator), ABS (denominator) result + = s TR (DVD/DVS) DVD%= DVS if DVD > 0: result + = "." Lookup = {} While DVD and DVD isn't in lookup: Lookup[dvd] = Len (result) DVD *= result + = str (dvd/d VS) DVD%= DVS if DVD in lookup: result = Result[:lookup[dvd]] + "(" + Result[lookup[dvd]:] + ")" Retu RN Result
C++:
Upgraded parameter typesstring fractiontodecimal (int64_t N, int64_t d) { //zero numerator if (n = = 0) return " 0 "; string res; Determine the sign if (N < 0 ^ D < 0) Res + = '-'; Remove sign of operands n = ABS (n), d = ABS (d); Append integral part res + = to_string (n/d); In case no fractional part if (n% d = = 0) return res; Res + = '. '; Unordered_map<int, int> map; Simulate the division process for (int64_t r = n D, r; R%= D) { //meet a known remainder //So we re Ach the end of the repeating part if (Map.count (R) > 0) { res.insert (Map[r], 1, ' ('); Res + = ') '; break; } The remainder is first seen //remember the current position for it map[r] = Res.size (); R *= Ten; Append the quotient digit res + = to_string (r/d); } return res;}
[Leetcode] 167. Fraction to recurring Decimal score turn repeating decimal