标签:
题目描述:public class Solution { public string FractionToDecimal(int numerator, int denominator) { if (numerator == 0) return "0"; if (denominator == 0) return ""; var result = ""; // is result is negative if ((numerator < 0) ^ (denominator < 0)) { result += "-"; } // convert int to long long num = numerator, den = denominator; num = Math.Abs(num); den = Math.Abs(den); // quotient long res = num / den; result += res.ToString(); // if remainder is 0, return result long remainder = (num % den) * 10; if (remainder == 0) return result; // right-hand side of decimal point Dictionary<long, int> map = new Dictionary<long, int>(); result += "."; while (remainder != 0) { // if digits repeat if (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; } // continue map.Add(remainder, result.Length); res = remainder / den; result += res.ToString(); remainder = (remainder % den) * 10; } return result; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode -- Fraction to Recurring Decimal
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48575985