166分数到小数(哈希表)

1、题目描述

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。

如果小数部分为循环小数,则将循环的部分括在括号内。

2、示例

输入: numerator = 2, denominator = 3
输出: "0.(6)"

3、题解

基本思想:HashMap,HashMap为余数和当前余数对应商所在res位置的映射,当在HashMap中找到出现过的余数时,说明有小数开始循环,通过余数找到对应开始循环的位置加入左括号(。

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<unordered_map>
using namespace std;
class Solution {
public:
	string fractionToDecimal(int numerator, int denominator) {
		//基本思想:HashMap,HashMap为余数和当前余数对应商所在res位置的映射
		//当在HashMap中找到出现过的余数时,说明有小数开始循环,通过余数找到对应开始循环的位置加入左括号(
		if (numerator == 0)
			return "0";
		string res;
		unordered_map<int, int> HashMap;
		//q为两数相除的商,r为两数相除的余数
		long long q, r, x, y;  //防止-INT_MIN/1的情况,因为INT_MIN的范围大于INT_MAX
		int pos;
		//算术显示强制转换效率更高
		x = static_cast<long long>(numerator);
		y = static_cast<long long>(denominator);
		if ((x > 0) ^ (y > 0))    //x和y不同号加入负号
			res += "-";
		x = llabs(x);
		y = llabs(y);
		q = x / y;
		r = x % y;
		res += to_string(q);
		if (r == 0)
			return res;
		res += ".";
		while (HashMap.find(r) != HashMap.end())
		{
			HashMap[r] = res.size();
			q = r;
			q *= 10;
			r = q % y;
			q = q / y;
			res += to_string(q);
			if (r == 0)
				return res;
		}
		res.insert(HashMap[r], "(");
		res += ')';
		return res;
	}
};
int main()
{
	Solution solute;
	int numerator = -2147483648, denominator = 1;
	cout << solute.fractionToDecimal(numerator, denominator) << endl;
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值