• LeetCode 166. Fraction to Recurring Decimal(模拟)


    题目

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

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

    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;
            
        }
    };
    
  • 相关阅读:
    [无聊测试赛] T12 道路
    [无聊测试赛] T9 矩阵覆盖
    [无聊测试赛] T10 所驼门王的宝藏
    [无聊测试赛] T8 佳佳的魔法药水
    [无聊测试赛] T7 豪华游轮
    [无聊测试赛] T6 排行榜
    【模板】三分求函数极值
    树的重心模板
    倍增最近公共祖先(LCA)
    ccf201612题解
  • 原文地址:https://www.cnblogs.com/dacc123/p/12236047.html
Copyright © 2020-2023  润新知