zoukankan      html  css  js  c++  java
  • Fraction to Recurring Decimal

    Total Accepted: 23332 Total Submissions: 166240 Difficulty: Medium

    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 fractionToDecimal(int numerator, int denominator) {
            if(numerator==0){
                return "0";
            }
            string res;
            int index = 0;
            if( ((numerator>>31)&1)^((denominator>>31)&1)){//异号
                res.push_back('-');
                index++;
            }
            long long int num = numerator;//long long int 防止溢出
            long long int den = denominator;
            num = fabs(num);
            den = fabs(den);
            
            int start=0;//无限循环小数的左括号的位置
            bool first = true;  //是否需要加小数点的标志
            unordered_map<long long int,int> numers;//用于判断被除数是否出现过
            while(num){
                if(numers[num] != 0){
                    start = numers[num]-1;
                    break;
                }
                numers[num] = index+1;
                if(num/den != 0){
                    string tmp = to_string(num/den);
                    res.append(tmp.begin(),tmp.end());
                    index += tmp.size();
                }else{
                    res.push_back('0');
                    index++;
                }
                long long int remaind = num%den;
                if(remaind!=0 && first){
                    res.push_back('.');
                    index++;
                    first = false;
                }
                num = remaind*10;
            }
            if(start!=0){
                res.insert(res.begin()+start,'(');
                res.push_back(')');
            }
            return res;
        }
    };
  • 相关阅读:
    二维凸包
    luogu_P1287 盒子与球
    luogu_P1993 小K的农场
    luogu_P1712 [NOI2016]区间
    luogu_P2444 [POI2000]病毒
    luogu_P2154 [SDOI2009]虔诚的墓主人
    20191005-T3-U91353 放射性
    编译原理 笔记2 词法分析
    DFA到等价正则表达式的转化
    软件分析笔记10 Soundiness
  • 原文地址:https://www.cnblogs.com/zengzy/p/5052096.html
Copyright © 2011-2022 走看看