Fraction to recurring Decimal
2015.1.23 15:59
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) ".
Solution:
First of all, the denominator won ' t is 0. Next you should take care for the sign first, + or-and make it positive.
3% 5 = = 3
5% 3 = = 2
6% 3 = = 0
The process of calculating a rational fraction is actually by division and modulus. If the remainder is zero, you get a finite fraction, otherwise an infinite loop. There ' s gonna be a loop as long as it is rational fraction. So, you'll have to record the remainder sequence, with a hash table maybe. When the same remainder are encountered, you know you ' ve found the loop sequence.
Also there ' s something to being careful about printing. Like the following.
5/3 = = 1. (6)
0/3 = = 0
6/3 = = 2
1/7 = = 0. (142857)
The denominator can is really large, so don ' t try to use a int A[MAXN] to record the sequence, it won ' t do. That's why I suggest hashing.
The time complexity was generally O (denominator), but should was much smaller in fact. The fraction 1/n May has a loop sequence of at the very n-1 in length, but usually far shorter. Space complexity is the same scale.
Accepted Code:
1 //1RE, 1TLE, 3MLE, 1AC, watch out for boundary cases and memory limit2#include <iostream>3#include <string>4#include <vector>5#include <unordered_map>6 using namespacestd;7 8typedefLong Long intll;9 Ten classSolution { One Public: A stringFractiontodecimal (intNumerator,intdenominator) { -ll n =numerator; -ll d =denominator; the - intsn, SD; - -SN = n >=0?1: -1; +n = n >=0? N:-N; -SD = d >=0?1: -1; +D = d >=0? D:-D; A at if(n = =0) { - return "0"; - } - - stringres =""; - if(SN * SD <0) { inRes.push_back ('-'); - } to +ll q = n/D; -ll r = ND; the *Res + =to_string (q); $ Panax Notoginseng if(r = =0) { - returnRes; the } + ARes.push_back ('.'); the intpos = (int) res.length (); + -Unordered_map<ll,int>seq; $Unordered_map<ll,int>:: iterator it; $ - while(r! =0) { -it =Seq.find (r); the if(It! =Seq.end ()) { -Res.insert (It->second,"(");WuyiRes.push_back (')'); the returnRes; - } WuSEQ[R] =Pos; -Q = R *Ten/D; AboutR = R *Ten%D; $Res.push_back ((int) Q +'0'); -++Pos; - } - A seq.clear (); + returnRes; the } - Private: $ }; the /* the int main () the { the int n, D; - solution Sol; in the While (CIN >> n >> d) { the cout << sol.fractiontodecimal (n, D) << Endl; About } the the return 0; the } + */
Leetcode-fraction to recurring Decimal