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 };
  • 相关阅读:
    Java8新特性简介
    责任链模式
    Bean的生命周期
    APP中https证书有效性验证引发安全问题(例Fiddler可抓https包)
    程序员成长指南
    Go 代码性能优化小技巧
    Go slice 扩容机制分析
    一次 Go 程序 out of memory 排查及反思
    curl 常用操作总结
    Go benchmark 详解
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5806218.html
Copyright © 2011-2022 走看看