Fraction to Recurring Decimal(分数转有理数)

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

 

/* 分数转小数 结果存为字符串, 如果有循环部分, 用括号括起来
 *
 * 数是 当前除的余数十倍时开始循环?
 *
 * 2/3 -> 20/3 = 6 余2 2/3继续
 *
 * 分别计算整数部分(取绝对值)符号部分 小数部分
 * 设立map记录余数和其出现位置的关系, 当前余数第二次出现时 就在第一次出现的位置前和 该位置后插入"(" ")"
 * */
class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        bool upNeg=numerator<0, downNeg=denominator<0;
        long long up=abs((long long)numerator), down=abs((long long)denominator), remain=up%down;
        string ret=to_string(up/down), left="";
        if(upNeg ^ downNeg && up && down) ret = "-" + ret;// &&up原因是结果为0时不应该有负号
        unordered_map<long long, int> m;
        int pos=0;// 记录小数出现的位置, left就是小数部分
        while(remain != 0){
            if(m.count(remain) != 0){
                left.insert(m[remain], "(");
                left += ")"; // 此处用insert(pos, ")")会出错, 上面Insert之后后面部分整体移动, insert 到pos+1位置
                break;
            }
            m[remain] = pos++;
            left += to_string((remain*10)/down);
            remain = (remain*10)%down;
        }
        if(left=="")    return ret;
        else    return ret+"."+left;
    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值