Skip to content

Commit

Permalink
impl fraction to decimal
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Mar 9, 2024
1 parent ec243d4 commit 2c87c3e
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion leetcode-cc/FractionToDecimal.hpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <unordered_map>

#include "TestHelper.h"
#include "problem.h"
#include "solution.h"
Expand Down Expand Up @@ -28,5 +30,39 @@ class SFractionToDecimal : public ISolution {
int benchmark() const override { return 0; }

private:
string fractionToDecimal(int numerator, int denominator) const {}
string fractionToDecimal(int numerator, int denominator) const {
if (numerator == 0) return "0";

string result;

if ((numerator < 0) ^ (denominator < 0)) result += '-';

long long num = abs((long long)numerator);
long long den = abs((long long)denominator);

result += to_string(num / den);

long long remainder = num % den;
if (remainder == 0) return result;

result += '.';

unordered_map<long long, int> map;
while (remainder != 0) {
// begin recurring
if (map.find(remainder) != map.end()) {
result.insert(map[remainder], "(");
result += ')';
break;
}

map[remainder] = result.size();

remainder *= 10;
result += to_string(remainder / den);
remainder %= den;
}

return result;
}
};

0 comments on commit 2c87c3e

Please sign in to comment.