#define _MAX 10000
int find(long long *_con, long long *_rem, long long _c, long long _r, int _cr_len, int *_pos)
{
int i=0;
for (i=0; i<_cr_len; i++)
{
if (_con[i]==_c && _rem[i]==_r)
{
*_pos = i;
return 0;
}
}
return -1;
}
char * fractionToDecimal(int numerator, int denominator)
{
int k = 0;
long long kn = 0;
int cr_len = 0;
int pos = -1;
long long Int = 0;
int ne_flag_n = 1, ne_flag_d = 1;
long long con[_MAX] = {0};
long long rem[_MAX] = {0};
if (denominator == 0)
return NULL;
if (numerator==-2147483648 && denominator==-1)
{
char *rexin = (char *)malloc(32);
memset(rexin, 0, 32);
snprintf(rexin, 32, "2147483648", 2147483648);
return rexin;
}
Int = numerator/denominator;
if (numerator%denominator == 0)
{
char *rexin = (char *)malloc(32);
memset(rexin, 0, 32);
snprintf(rexin, 32, "%d", Int);
return rexin;
}
if (numerator < 0)
{
ne_flag_n = -1;
if (numerator>-2147483648)
numerator = -numerator;
}
if (denominator < 0)
{
ne_flag_d = -1;
if (denominator>-2147483648)
denominator = -denominator;
}
if (numerator > denominator || numerator==-2147483648)
{
numerator = numerator%denominator;
}
kn = numerator*10;
printf("ssss[%d]\n", denominator);
for (k=0; k<_MAX; k++)
{
if (find(con, rem, kn/denominator, kn%denominator, cr_len, &pos) == 0)
break;
con[k] = kn/denominator;
rem[k] = kn%denominator;
cr_len++;
kn = rem[k]*10;
}
printf("pos :%d\n", pos);
char * ret = (char *)malloc(_MAX);
char tmp_c[2] = {0};
memset(ret, 0, _MAX);
if (ne_flag_n*ne_flag_d < 0 && Int >= 0)
{
snprintf(ret, _MAX, "-%d.", Int);
}
else
{
snprintf(ret, _MAX, "%d.", Int);
}
if (pos == -1)
{
for (k=0; k<_MAX; k++)
{
if (con[k] < 0)
{
snprintf(tmp_c, 2, "%lld", -con[k]);
}
else
{
snprintf(tmp_c, 2, "%lld", con[k]);
}
strcat(ret, tmp_c);
}
}
else
{
for(k=0; k<pos; k++)
{
if (con[k] < 0)
{
snprintf(tmp_c, 2, "%lld", -con[k]);
}
else
{
snprintf(tmp_c, 2, "%lld", con[k]);
}
strcat(ret, tmp_c);
}
if (cr_len-pos==1 && con[pos]==0)
return ret;
strcat(ret, "(");
for(k=pos; k<cr_len; k++)
{
if (con[k] < 0)
{
snprintf(tmp_c, 2, "%lld", -con[k]);
}
else
{
snprintf(tmp_c, 2, "%lld", con[k]);
}
strcat(ret, tmp_c);
}
strcat(ret, ")");
}
return ret;
}