LeetCode 166 Fraction to Recurring Decimal

标签: 数学类题目 LeetCode 发布于:2022-03-04 23:31:33 编辑于:2022-03-04 23:31:33 浏览量:987

概述

https://leetcode.com/problems/fraction-to-recurring-decimal/

模拟除法 + 哈希表查重

实现的时候注意:

  1. 注意负数的情况;
  2. 因为我们把负数做了 abs 处理,所以存在溢出的风险(没错,就给你 -2147483648 恶心你);

四连 WARE,绝绝子。

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) return "0";
        bool neg = false;
        long nume = numerator;
        long deno = denominator;
        if (nume * deno < 0) neg = true;
        nume = abs(numerator);
        deno = abs(denominator);
        unordered_map<int, int> m;
        string ans;
        int i = 0;
        bool afterDot = false;
        while (true) {
            if (afterDot) {
                if (m.count(nume)) {
                    ans.insert(m[nume], "(");
                    ans += ")";
                    break;
                }
                m[nume] = i;
                i ++;
            }
            long a = nume / deno;
            ans += to_string(a);
            nume -= a * deno;
            if (nume == 0) break;
            nume *= 10;
            if (!afterDot) {
                afterDot = true;
                ans += ".";
                i = ans.size();
            }
        }
        if (neg) return "-" + ans;
        return ans;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/