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)".

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0)
	    {
		    return "0";
	    }

	    string result;
	    if ((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0))
	    {
		    result += "-";
	    }
	    long long num = numerator;
	    long long den = denominator;
	    if (num < 0)
	    {
		    num = -num;
	    }
	    if (den < 0)
	    {
		    den = -den;
	    }

	    unsigned int left = num / den;
	    num = num % den;
	    char str[20];
	    sprintf(str, "%u", left);
	    result += str;
	    if (num == 0)
	    {
		    return result;
	    }
	    else
	    {
		    result += ".";
	    }

	    map<long long, long long> buf;
	    string right;
	    int offset = 0;
	    while (num != 0)
	    {
		    map<long long, long long>::iterator it = buf.find(num);
		    if (it == buf.end())
		    {
			    buf[num] = offset;
			    offset++;
			    num *= 10;
			    int temp = num / den;
			    right += temp + '0';
			    num %= den;
		    }
		    else
		    {
			    result += right.substr(0, buf[num]) + "(" + right.substr(buf[num], string::npos) + ")";
			    return result;
		    }
	    }

	    return result + right;
    }
};


你可能感兴趣的:(Fraction to Recurring Decimal)