跳至主要内容

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;
    }

};

评论

此博客中的热门博文

ncurses与readline结合

  #define _XOPEN_SOURCE 700       /* for wcswidth and 700 is for mbsnrtowcs */ #include<wchar.h> #include<ncurses.h>       /* ncurses.h includes stdio.h */ #include<stdlib.h> #include<string.h> #include<readline/readline.h> #include<locale.h>     int mygetstr( char *str, int y, int x){    WINDOW *win;    int size, col;    int ok = 0;    int width;    wchar_t wstr[80];    char *p;        getmaxyx(stdscr, size, col);        void getaline( char *s){      str = s;      rl_callback_handler_remove();      ok = 1;    }        rl_callback_handler_install( "" , getaline);    win = newwin(1, col-x, y, x);    while (1){      rl_callback_read_char(); ...

利用yellowdns解决dns污染问题

 很多网站的dns直接被污染成了127.0.0.1,这样一般就无法访问了,很多翻墙软件也认为是局域网,所以访问不了 这时候,使用yellowdns,将dns转发到远程。然后listen本地的53端口。再将dns服务器都改成本地 vi /etc/resolv.conf windows和路由器,也可以都更改