前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 166. Fraction to Recurring Decimal(模拟)

LeetCode 166. Fraction to Recurring Decimal(模拟)

作者头像
ShenduCC
发布2020-02-14 18:08:20
3230
发布2020-02-14 18:08:20
举报
文章被收录于专栏:算法修养算法修养

题目

题意:给出一个分数的分子和分母,给出这个分数的小数形式的字符串模式。循环的部分用( 括上。

题解:模拟除法,判断循环体。

代码语言:javascript
复制
class Solution {
public:
    map<int,int> m;
    string fractionToDecimal(int numerator, int denominator) {
       long long int numerator_ = numerator;
       long long int denominator_ = denominator;
        int sign = 1;
        if(numerator_<0&&denominator_>0)
        {
            sign = 0;
        }
       
        else if(numerator_>0&&denominator_<0)
        {
            
            sign = 0;
        }
        
         if(numerator_<0)
            numerator_ *= -1;
        
        if(denominator_<0)
            denominator_ *= -1;

       string ans="";
    

       if(numerator_ > denominator_)
       {
           long long int x = numerator_ / denominator_;
           numerator_ = numerator_ % denominator_;  
           ans += to_string(x);
       }
       else
       {
           ans += '0';
       }
        
         m[numerator_] = 1;
        
       if(numerator_!=0) 
        ans+='.';
        
       int tag=1;
       int pos=0;
        
       while(numerator_!=0)
       {
           numerator_ *= 10;
           
           long long int  x = numerator_ / denominator_ ;
           
           ans += (x+'0');

           numerator_ = numerator_ % denominator_;  
           
           if(numerator_==0)
               break;
           
           if(m[numerator_]!=0)
           {
               pos = m[numerator_];
               break;
           }
           else
           {
               m[numerator_]=++tag;
           }
       }
        
        
        string res="";
        if(sign==0)
            res += '-';
        int i;
        tag=-1;
        int tag2=0;
        for(i=0;i<ans.length();i++)
        {
            
            
            if(tag==pos)
            {
                res+='(';
                tag2=1;
            }
            
            res+=ans[i];
            
            if(tag>=1)
            {
                tag++;
            }
            
            if(ans[i]=='.')
            {
                tag=1;
            }
        }
        
        if(tag2==1)
        res+=')';
        
        return res;
        
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-01-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档