zoukankan      html  css  js  c++  java
  • leetcode[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)".

    class Solution {
    public:
    string  to_str(long long  n)
    {
        string str="";
        if(n==0)
        {
            str+='0';
            return str;
        }
        long long tmp=n;
        long long power=1;
        int icount=0;
        while (tmp)
        {
            tmp/=10;
            power*=10;
            icount++;
        }
        power/=10;
        tmp=n;
        for (int i=0;i<icount;i++)
        {
            long long d=tmp/power;
            str+=char('0'+d);
            tmp-=d*power;
            power/=10;
        }
        return str;
    }
    string fractionToDecimal(int numerator, int denominator) {
        if(denominator==0)return "";
        if(numerator==0)return "0";
        string res="";
        long long num=numerator,  den=denominator;
        if((num>0&&den<0)||(num<0&&den>0))
            res+="-";
        num=num>=0?num:-num,den=den>=0?den:-den;
        long long part=num/den;
        res+=to_str(part);
        long long f=num%den;
        if(f==0)return res;
        res+='.';
        map<int,int> fmap;
        while(f)
        {
            if (fmap.count(f))
            {
                int beg=fmap[f];
                string part1=res.substr(0,beg);
                string part2=res.substr(beg,res.length());
                res=part1+"("+part2+")";
                return res;
            } 
            else
            {
                fmap[f]=res.length();            
                f*=10;
                res+=to_str(f/den);
                f%=den;        
            }
        }
        return res;
    }
    };
  • 相关阅读:
    【无中生有】---4----数据库设计-3
    【无中生有】---2---数据库设计-1
    redis3.0的demo实验
    redis3.0的demo实验
    那些在学习iOS开发前就应该知道的事(part 1)
    模板文件中的插件嵌入点列表
    图像处理框架 Core Image 介绍
    sharepoint services
    DiscuzX2.5数据库字典 值得学习
    Sublime Text 使用技巧
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4280677.html
Copyright © 2011-2022 走看看