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

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

    思路:模拟除法。用一个map记录在哪个位置余数开始出现重复,从而可以插入‘(’。

     1 class Solution {
     2 public:
     3     string fractionToDecimal(int numerator, int denominator) {
     4         if (numerator == 0) return "0";
     5         string res;
     6         //calculate the sign
     7         if (numerator < 0 ^ denominator < 0) res += '-';
     8         int64_t n = abs((int64_t)numerator);
     9         int64_t d = abs((int64_t)denominator);
    10         
    11         //get the value before '.'
    12         res += std::to_string(n / d);
    13         if (n % d == 0) return res;
    14         
    15         res += '.';
    16         //use map to keep index, so that we know where to insert the '('
    17         unordered_map<int64_t, int> remains;
    18         for (int64_t r = n % d; r; r %= d) {
    19             if (remains.count(r) > 0) {
    20                 res.insert(remains[r], "(");
    21                 res += ')';
    22                 break;
    23             }
    24             remains.insert(make_pair(r, res.size()));
    25             r *= 10;
    26             res += std::to_string(r / d);
    27         }
    28         return res;
    29     }
    30 };
  • 相关阅读:
    RabbitMQ简介、特性、使用场景、安装、启动与关闭
    mybatis的工作原理
    bzoj2119 股市的预测
    Noi2014 购票
    51Nod 算法马拉松22 开黑记
    COGS2485 从零开始的序列
    Codeforces Round #402 (Div.2)
    BestCoder Round #92
    COGS2294 释迦
    bzoj4764 弹飞大爷
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5806218.html
Copyright © 2011-2022 走看看