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;
        }
    };
  • 相关阅读:
    微博深度学习平台架构和实践
    2020暑期学习
    2020春季学期个人课程总结
    人月神话阅读笔记03
    人月深化阅读笔记02
    第十六周学习总结
    人月神话阅读笔记01
    三分算法
    [SDOI2010]魔法猪学院
    【洛谷】NOIP2018原创模拟赛DAY1解题报告
  • 原文地址:https://www.cnblogs.com/zengzy/p/5052096.html
Copyright © 2011-2022 走看看