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) ".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
Hide TagsHash Table Math The topic is actually very easy, need to consider is overflow problem, long int length is 32 bits, long long int is 64 bit.
#include <iostream>#include<unordered_map>#include<string>#include<sstream>using namespacestd;classSolution { Public: stringFractiontodecimal (intNumerator,intdenominator) { BOOLFlag1 = numerator<0; BOOLFlag2 = denominator<0; unsigned numer= flag1?-Numerator:numerator; unsigned denom= flag2?-Denominator:denominator; if(denom==0)return ""; if(numer==0)return "0"; StringStream SS; SS<<numer/Denom; stringRET =Ss.str (); unsignedLong Long intLFT = numer%Denom; Unordered_map<unsignedint, unsignedint>MP; stringret1=""; unsignedintCNT =1; while(LFT) {if(mp[lft]==0) {Mp[lft]=cnt++; Ret1+ = (lft*Ten)/denom +'0'; LfT= (lft*Ten)%Denom; Continue; } Ret1= Ret1.substr (0, mp[lft]-1) +"("+ RET1.SUBSTR (mp[lft]-1) +")"; Break; } if(Ret1! ="") ret + ="."+Ret1; if(FLAG1^FLAG2) ret ="-"+ret; returnret; }};intMain () {solution Sol; cout<<sol.fractiontodecimal (-1,-2147483648) <<Endl; return 0;}
[Leetcode] Fraction to recurring Decimal hash table