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.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
这道题可以按照正常的除法计算方法来。使用一个哈希表来保存每次得到的余数,如果遇到相同的余数,说明小数部分开始重复。
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string res;
unordered_map<int,int> data;
if(numerator == 0)
return "0";
long numerator_1 = numerator;
long denominator_1 = denominator;
//获取结果的符号
if((numerator ^ denominator) < 0)
res.push_back('-');
numerator_1 = abs(numerator_1);
denominator_1 = abs(denominator_1);
long integer = numerator_1 / denominator_1;
long remainder = numerator_1 % denominator_1;
res += to_string(integer);
if(remainder == 0){
return res;
}
res += '.';
string digit = "";
int beginId = 0;
while(remainder != 0 && data.find(remainder) == data.end()){
data[remainder] = beginId++;
remainder *= 10;
long devideRes = remainder / denominator_1;
remainder = remainder % denominator_1;
digit += to_string(devideRes);
}
if(remainder == 0){
res += digit;
return res;
}
else{
int index = data[remainder];
digit.insert(index, 1, '(');
digit.push_back(')');
res += digit;
return res;
}
}
};
网友评论