跳至主要内容

166. 分数到小数

class Solution {
public:
   
    string itoa(long long i)
    {
        char buff[100];
        sprintf(buff, "%lld", i);
        return buff;
    }

    string fractionToDecimal(int num, int den) {

        long long numerator = num;
        long long denominator = den;

        int neg = 1;
        if (numerator > 0 && denominator < 0)
        {
            neg = -1;
        }
        if (numerator < 0 && denominator > 0)
        {
            neg = -1;
        }
        numerator = abs(numerator);
        denominator = abs(denominator);

        long long a = numerator / denominator;
        if (numerator == a * denominator)
        {
            return (neg<0?"-":"")+itoa(a);
        }
        string ret = (neg<0?"-":"")+itoa(a);
        ret += ".";
        long long left = numerator - a * denominator;

        vector<pair<int, int>> c;
        int loop = -1;
        while (left != 0)
        {
            left *= 10;
            a = left / denominator;
            for (int i = 0; i < c.size(); i++)
            {
                if (c[i].first == a && c[i].second == left)
                {
                    loop = i;
                    break;
                }
            }

            if (loop != -1)
            {
                break;
            }

            if (left < denominator)
            {
                c.push_back(make_pair(a,left));
                continue;
            }
            c.push_back(make_pair(a, left));
            left = left - a * denominator;
            if (left == a * denominator)
            {
                break;
            }
        }

        for (int i = 0; i < c.size(); i++)
        {
            if (loop == i)
            {
                ret += "(";
            }
            ret += itoa(c[i].first);
        }

        if (loop != -1)
        {
            ret += ")";
        }

        return ret;
    }

};

评论

此博客中的热门博文

ubuntu 添加root登录

Login to your server as root. As the root user, edit the sshd_config file found in  /etc/ssh/sshd_config : vim /etc/ssh/sshd_config ( For details on working with Vim check out our article here !) Add the following line to the file, you can add it anywhere but it’s good practice to find the block about authentication and add it there. PermitRootLogin yes Save and exit the file. Restart the SSH server: systemctl restart sshd or service sshd restart