From a1d801a897938a06feefa29e45c6012f8a8c6a25 Mon Sep 17 00:00:00 2001 From: chayan das Date: Wed, 24 Sep 2025 14:33:44 +0530 Subject: [PATCH] Create 166. Fraction to Recurring Decimal --- 166. Fraction to Recurring Decimal | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 166. Fraction to Recurring Decimal diff --git a/166. Fraction to Recurring Decimal b/166. Fraction to Recurring Decimal new file mode 100644 index 0000000..abb82c1 --- /dev/null +++ b/166. Fraction to Recurring Decimal @@ -0,0 +1,34 @@ +class Solution { +public: + string fractionToDecimal(int numerator, int denominator) { + + if (numerator == 0) return "0"; + string res; + if ((numerator < 0) ^ (denominator < 0)) res.push_back('-'); + + long long n = llabs((long long)numerator); + long long d = llabs((long long)denominator); + + res += to_string(n / d); + long long rem = n % d; + if (rem == 0) return res; + + res.push_back('.'); + unordered_map seen; + + while (rem != 0) { + if (seen.find(rem) != seen.end()) { + int pos = seen[rem]; + res.insert(pos, "("); + res.push_back(')'); + break; + } + seen[rem] = res.size(); + rem *= 10; + int digit = rem / d; + res.push_back(char('0' + digit)); + rem = rem % d; + } + return res; + } +};