我也贴个我的, 直接计算出了循环节出现的位置, 因此是O(1)空间.
我是直接用cout输出的, 没有转成string.
int gcd(int i, int j)
{
return j ? gcd(j, i%j ) : i;
}
// Print N/D, e.g. 10/5 = 2.0, 2/4 = 0.5, 1/6 = 0.1(6)
void fracdec(int N, int D){
// Get rid of common divisor
int d1 = gcd(N, D);
N /= d1;
D /= d1;
int I = N/D; // Integer part
cout << I << '.';
if( N%D == 0){
cout << 0 << endl;
return;
}
// Compute multiplicity of 2 and 5 in D
int m2 = 0, m5 = 0, D1 = D;
while( D1%2 == 0){
m2++;
D1 /= 2;
}
while( D1%5 == 0){
m5++;
D1 /= 5;
}
int m = (m2 > m5)? m2 : m5;
// After printing out integer part I, the number becomes N1/D
int N1 = N % D;
// Eliminate 2 and 5 in D by multiplying N1 by 10;
for(int i = 0; i < m; i++){
N1 *= 10;
cout << N1/D;
N1 %= D;
}
// If D has no other factors
if(N1 == 0){
cout << endl;
return;
}
// Print the repeated pattern
int r = N1;
cout << '(';
do{
r *= 10;
cout << r/D;
r %= D;
}while( r != N1 );
cout << ')' << endl;
}