• leetcode 166. Fraction to Recurring Decimal


    166. Fraction to Recurring Decimal

    https://www.cnblogs.com/grandyang/p/4238577.html

    用一个哈希表判断余数是否重复,重复了就有无限循环小数,就可以停止加括号了

    class Solution {
    public:
        string fractionToDecimal(int numerator, int denominator) {
            int flag1 = numerator > 0 ? 1 : -1;
            int flag2 = denominator > 0 ? 1 : -1;
            long num1 = abs((long)numerator);
            long num2 = abs((long)denominator);
            long num = num1 / num2;
            long rem = num1 % num2;
            unordered_map<int,int> m;
            string res = to_string(num);
            if(flag1 * flag2 == -1 && (num != 0 || rem != 0))
                res = "-" + res;
            if(rem == 0)
                return res;
            res += ".";
            int index = res.size();
            while(rem){
                if(m.find(rem) != m.end()){
                    res.insert(m[rem],"(");
                    res += ")";
                    return res;
                }
                m[rem] = index;
                num = rem*10 / num2;
                rem = rem*10 % num2;
                res += to_string(num);
                ++index;
            }
            return res;
        }
    };

    自己又写了一遍

    class Solution {
    public:
        string fractionToDecimal(int numerator, int denominator) {
            if(denominator == 0)
                return "";
            bool flag;
            if((numerator >= 0 && denominator > 0) || (numerator <= 0 && denominator < 0))
                flag = true;
            else
                flag = false;
            long num1 = abs((long)numerator);
            long num2 = abs((long)denominator);
            long num = num1/num2;
            long rem = num1%num2;
            string res;
            res += to_string(num);
            if(!flag)
                res = "-" + res;
            if(rem == 0)
                return res;
            res += ".";
            unordered_map<long,int> m;
            int index = res.size();
            while(rem != 0){
                if(m.find(rem) != m.end()){
                    res.insert(m[rem],"(");
                    res += ")";
                    return res;
                }
                m[rem] = index;
                long tmp = rem*10/num2;
                rem = rem*10%num2;
                res += to_string(tmp);
                index++;
            }
            return res;
        }
    };
  • 相关阅读:
    ssm整合之配置applicationContext-service.xml
    ssm整合之配置applicationContext-dao.xml
    ssm整合之mybatis配置文件SqlMapConfig.xml
    ssm整合之导包
    java BigDecimal工具类
    java中json依赖包
    Servlet+Json代码
    xstream+dom4j比较对象
    分析堆栈跟踪元素
    myeclipse搭建activemq 简单聊天
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10937570.html
Copyright © 2020-2023  润新知