• [LeetCode]Fraction to Recurring Decimal


    题目描述:

    Fraction to Recurring Decimal

    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)".

    解题思路:

    1. 要找出循环小数的序列,就需要找出相同的余数,则2个相同余数间计算出的小数就是循环小数;

    2. 因为需要在循环数列之间插入括号,所以要使用hash表记录出现各余数时对应结果中的位置。

    3. 该题目的数据比较大,使用int类型不够,需要使用int64_t类型。

    解题代码:

    class Solution {
    public:
        string fractionToDecimal(int64_t numerator, int64_t denominator) {
            string result = "";
            if(numerator * denominator < 0)
            {
                result += '-';
            }
            
            int64_t num = abs(numerator), den = abs(denominator);
            
            result += to_string(num / den);
            
            if(num % den == 0)
            {
                return result;
            }
            else 
            {
                result += '.';
            }
            
            int64_t rem = num % den;
            map<int, int> rem_map;
            while(rem != 0)
            {
                if(rem_map[rem] > 0)
                {
                    result.insert(rem_map[rem], 1, '(');
                    result += ')';
                    break;
                }
                
                rem_map[rem] = result.size();
                rem *= 10;
                result += to_string(rem / den);
                rem %= den;
            }
            
            return result;
        }
    };
  • 相关阅读:
    jquery实现章节目录效果
    Delphi里如何让程序锁定在桌面上,win+d都无法最小化
    php 之跨域上传图片
    delphi判断文件类型
    EmptyRecycle() 清空回收站
    delphi检查url是否有效的方法
    Explode TArray
    css设置中文字体(font-family:"黑体")后样式失效问题
    javascript-lessons
    课后作业2
  • 原文地址:https://www.cnblogs.com/liuyikang/p/4351170.html
Copyright © 2020-2023  润新知