Leetcode 166. Fraction to Recurring Decimal 弗洛伊德判环

时间:2021-07-23 21:44:14

分数转小数,要求输出循环小数 如2 3 输出0.(6)

弗洛伊德判环的原理是在一个圈里,如果一个人的速度是另一个人的两倍,那个人就能追上另一个人。代码中one就是速度1的人,而two就是速度为2的人。

Fraction to Recurring Decimal可以使用弗洛伊德判环,不同的是要找到循环出现的起始点,因此会比单单判断是否循环出现的题要难一点,代码要长一点,但是它比是用map的实现会更快。

要做出这道题有几个注意点:

1)对于整数的求余和整除运算要注意,特别负数的求余运算, 可以参考 getMode_()和getShang_();

2) 由于整数整除的特殊性,对于整数整除是0的无法判断正负,因此要转化成double再判断;

3)对于弗洛伊德判环请注意退出条件和找到循环出现的起始点和结束点,注意初始化。

 class Solution {
public:
typedef long long __int64;
inline __int64 getShang_(__int64 numerator, __int64 denominator){//特别注意数字都要取绝对值
return abs(numerator) / abs(denominator);
} inline __int64 getMod_(__int64 numerator, __int64 denominator){//特别注意数字都要取绝对值
return abs(numerator) % abs(denominator);
} inline std::string inttostr_(__int64 num){
char t[] = { };
sprintf(t, "%lld", num);
return std::string(t);
} std::string fractionToDecimal(int numerator, int denominator) {
std::string Integer_("");
if ((double)numerator / denominator < ) Integer_ = "-"; //整数整除是0的无法判断正负
Integer_ += inttostr_(getShang_(numerator, denominator)); if ( == getMod_(numerator,denominator) ) {
return Integer_;
}
Integer_ += ".";
__int64 tnumerator = numerator;
tnumerator = getMod_ (tnumerator, denominator);
//printf("%lld\n", numerator);
__int64 one = tnumerator;
__int64 two = tnumerator;
std::vector<__int64> vyushu;
std::string Decimal_("");
vyushu.push_back(two);
int cnt = ; //循环节周期
while (true)
{
one = getMod_(one * , denominator); Decimal_ += inttostr_(getShang_(two * , denominator));
two = getMod_(two * , denominator);
vyushu.push_back(two);
if ( == two) break;//退出条件 Decimal_ += inttostr_(getShang_(two * , denominator));
two = getMod_(two * , denominator);
vyushu.push_back(two);
if ( == two) break;//退出条件 cnt++;
if (two == one) break;
}
/*for (auto i:vyushu){
std::cout << i << std::endl;
}
std::cout << Decimal_ << std::endl;
std::cout << cnt << std::endl;*/
if (two){ //找到循环出现的起始点和结束点[j,k)
int j = , k = ;
for (std::vector<int>::size_type i = vyushu.size()-; i >= && i>=cnt; --i){
if (vyushu[ i -cnt] != vyushu[ i]){
j = i - cnt + ;
break;
}
}
for (std::vector<int>::size_type i = j + ; i < vyushu.size(); ++i){
if (vyushu[i] == vyushu[j]) {
k = i;
break;
}
}
//std::cout << j << " " << k << std::endl;
return Integer_ + Decimal_.substr(, j) + "(" + Decimal_.substr(j, k - j) +")";
}
else return Integer_ + Decimal_; }
};

在代码中注释部分出现的某些代码是来自c++11标准的,请忽略! 另外c++11标准直接支持__int64。