首页 > 代码库 > LeetCode Fraction to Recurring Decimal

LeetCode Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is 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:

 1    string fractionToDecimal(int numerator, int denominator) { 2         int neg = 0; 3         int flag = 0; 4         int recurring = 1; 5          if ((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0))  neg = 1; 6         unsigned long long num = (numerator == -2147483648)? 2147483648 : abs(numerator); 7         unsigned long long den = (denominator == -2147483648)? 2147483648 : abs(denominator); 8      9         unsigned long long integer = num / den;10         unsigned long long remain = num % den;11         flag = (remain == 0 ? 1 : 0);12     13         map<int, int> seen;14         seen[remain] = 0;15         vector<int> digits;16         while (1) {17             remain *= 10;18             digits.push_back(remain / den);19             remain = remain % den;20             recurring = (remain == 0) ? 0 : 1;21             if (seen.count(remain)) {22                 int where = seen[remain];23                 ostringstream os;24                 if (neg) {25                     os << -;26                 }27                 os << integer;28                 if (!flag) {29                     os << .;30                     for (int i = 0; i < where; ++i)31                     {32                         os << digits[i];33                     }34                     if (recurring)35                     {36                          os << (;37                         for (int i = where; i < digits.size(); ++i) 38                             os << digits[i];39                         os <<);40                     }41                    42                 }43     44                 return os.str();45             }46             else 47                 seen[remain] = digits.size();48     49         }50 51     }

 

LeetCode Fraction to Recurring Decimal