166. 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.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

此题的思路并不难,但是程序较复杂,各种情况都容易出错

我的代码:当处理1/90时,答案为0.0(11),应该是因子是10的倍数导致的

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        string left;
        string right;
        bool re=false;
        if(numerator==0) return left+"0";
        if(denominator==0) return left;
        unordered_map<int,int> hash;
        hash[numerator]=0;
        int first=0,last=0;
        if(numerator>=denominator)
        {
            left+=to_string(numerator/denominator);
            if(numerator%denominator)
            {
                fraction(numerator%denominator,denominator,right,numerator,re,hash,last,first);
            }
            
        }
        else
            {
                fraction(numerator,denominator,right,numerator,re,hash,last,first);
            }
        string res;
        if(!left.empty()) res+=left;
        else res+="0";
        if(!right.empty())
        {
            if(re) {
                res.push_back('.');
                for(int i=0;i<first;i++)
                {
                    res.push_back(right[i]);
                }
                res+="("+right.substr(first)+")";
            }
            else res+="."+right;
        }
        return res;
        
    }
    void fraction(int num,const int& de,string& right,const int& nu,bool& re,unordered_map<int,int>& hash,int& last,int& first){
        int zero=0;
        while(num<de)
        {
            zero++;
            num*=10;
        }
        int temp=num/de;
        int ba=zero;
        while(ba-->1)
        {
            right+="0";
        }
        right+=to_string(temp);
        last++;
        while(zero>nu&&zero%10==0)
        {
            zero/=10;
            
        }
        if(hash.find(num%de)!=hash.end()) {
            re=true;
            first=hash[num%de];
            return ;
        }
        if(num%de==0) return ;
        hash[num%de]=last;
        fraction(num%de,de,right,nu,re,hash,last,first);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值