C# solution: dictionary, overflow, "+"&"-"


  • 0
    B
    public class Solution 
    {
        public enum Sign{ Positive, Negative}
        public string FractionToDecimal(int numerator, int denominator) 
        {
            if (denominator == 0) return "";
            if (numerator == 0) return "0";
    
            var sign = Sign.Positive;
            if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0))
            {
                sign = Sign.Negative;
            }
    
            var longNumerator = Math.Abs((long)numerator);
            var longDenominator = Math.Abs((long)denominator);
    
            var integerPart = longNumerator / longDenominator;
    
            var remainder = longNumerator % longDenominator;
    
            if (remainder == 0) return $"{(long)numerator/(long)denominator}";
    
            var decimalPart = GetDecimalPart(Math.Abs(remainder), Math.Abs(longDenominator));
    
            if (sign == Sign.Positive)      return $"{integerPart}.{decimalPart}"; 
            else  return $"-{integerPart}.{decimalPart}"; 
        }
    
        private string GetDecimalPart(long remainder, long denominator)
        {
            var remainderAndIndex = new Dictionary<long, int>();
    
            var result = new StringBuilder();
    
            while(remainder != 0)
            {
                var oneResult = remainder * 10 / denominator;
    
                if (remainderAndIndex.ContainsKey(remainder))
                {
                    var preIndex = remainderAndIndex[remainder];
    
                    result.Insert(preIndex, "(");
                    result.Append(")");
    
                    return result.ToString();
                }
    
                result.Append(oneResult);
                remainderAndIndex[remainder] = result.Length - 1;
                
                remainder = remainder * 10 % denominator;
            }
    
            return result.ToString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.