166. 分数到小数

#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值