2025-09-24 Daily Challenge

Today I have done leetcode's September LeetCoding Challenge with cpp.

September LeetCoding Challenge 24

Description

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.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

 

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

 

Constraints:

  • -231 <= numerator, denominator <= 231 - 1
  • denominator != 0

Solution

class Solution {
public:
  string fractionToDecimal(int numerator, int denominator) {
    if(numerator == 0) return "0";

    string answer;
    if((numerator < 0) ^ (denominator < 0)) answer.push_back('-');

    long long devidend = abs<long long>(numerator);
    long long divisor = abs<long long>(denominator);
    answer += to_string(devidend / divisor);
    long long remainder = devidend % divisor;
    if(remainder == 0) return answer;
    
    answer.push_back('.');
    map<long long, int> remainders;
    while(remainder != 0) {
      if(remainders.count(remainder)) {
        answer.insert(remainders[remainder], "(");
        answer.push_back(')');
        break;
      }
      remainders[remainder] = answer.size();
      remainder *= 10;
      answer.push_back('0' + remainder / divisor);
      remainder %= divisor;
    }
    return answer;
  }
};

// Accepted
// 41/41 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 98.91 % of cpp submissions (8.3 MB)