首页 > 代码库 > 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)"           

 题目在意思上是比较简单的,就是计算商的值,比较麻烦的是如果遇到后面是无限循环小数,那么将循环的部分()起来

在寻找循环的过程中利用map结构 

在做除法的过程中,如果一步之后的余数之前已经出现过了,那么必然开始循环,而map需要记录的就是余数和余数第一次在

商结果中出现的位置,这样才能够比较方便的打上()

还有一个需要注意的就是,传入的数据可能是正数可能是负数,注意结果的符号

同时:INT类型的范围 -2147483648 ~  2147483647,所以如果还是用int类型保存其绝对值,对于-2147483648是没有办法的,所以要将类型转换到long long 类型

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
   return Helper(numerator, denominator);
    }
    string Helper(long long numerator, long long denominator)
{
	if(numerator == 0)
	{
		return "0";
	}
	if(denominator == 0)
	{
		return "";
	}
	string RetVal = "";
	if((numerator<0)^(denominator<0))
	{
		RetVal += "-";
	}
	numerator = abs(numerator);
	denominator = abs(denominator);
	long long integer = numerator/denominator;
	stringstream ss;
	ss << integer;
	RetVal += ss.str();
	if(numerator%denominator == 0)
	{
		return RetVal;
	}
	RetVal += ".";
	long long frac = numerator%denominator;
	map<long long,int> repeatMap;
	long long rest = frac;
	while(rest)
	{
		if(repeatMap.find(rest) != repeatMap.end())
		{
			RetVal.insert(repeatMap[rest],1,'(');
			RetVal += ')';
			return RetVal;
		}
		repeatMap[rest] = RetVal.size();
		stringstream s;
		s << ((rest*10)/denominator);
		RetVal += s.str();
		rest = (rest*10) % denominator;
	}
	return RetVal;
}
};


LeetCode—*Fraction to Recurring Decimal