假设我们有两个分别称为分子和分母的数字,它们表示形式为(分子/分母)的有理数。我们必须找到其十进制表示形式作为字符串。如果有重复出现的数字,请用方括号括起来。
因此,如果输入像 分子= 164,分母= 3,那么输出将是“ 54.(6)”
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; class Solution { public: string solve(int numerator, int denominator) { if (numerator == 0) return "0"; vector<char> ans; if (numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0) ans.push_back('-'); long divisor = labs(numerator); long dividend = labs(denominator); long remainder = divisor % dividend; string x = to_string(divisor / dividend); for (int i = 0; i < x.size(); i++) { ans.push_back(x[i]); } if (remainder == 0) { return string(ans.begin(), ans.end()); } ans.push_back('.'); map<int, int> m; while (remainder != 0) { if (m.find(remainder) != m.end()) { ans.insert(ans.begin() + m[remainder], '('); ans.push_back(')'); break; } else { m[remainder] = ans.size(); remainder *= 10; ans.push_back((remainder / dividend) + '0'); remainder %= dividend; } } return string(ans.begin(), ans.end()); } }; string solve(int numerator, int denominator) { return (new Solution())->solve(numerator, denominator); } int main() { cout << solve(164, 3); }
164, 3
输出结果
54.(6)