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)"
/* 分数转小数 结果存为字符串, 如果有循环部分, 用括号括起来
*
* 数是 当前除的余数十倍时开始循环?
*
* 2/3 -> 20/3 = 6 余2 2/3继续
*
* 分别计算整数部分(取绝对值)符号部分 小数部分
* 设立map记录余数和其出现位置的关系, 当前余数第二次出现时 就在第一次出现的位置前和 该位置后插入"(" ")"
* */
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
bool upNeg=numerator<0, downNeg=denominator<0;
long long up=abs((long long)numerator), down=abs((long long)denominator), remain=up%down;
string ret=to_string(up/down), left="";
if(upNeg ^ downNeg && up && down) ret = "-" + ret;// &&up原因是结果为0时不应该有负号
unordered_map<long long, int> m;
int pos=0;// 记录小数出现的位置, left就是小数部分
while(remain != 0){
if(m.count(remain) != 0){
left.insert(m[remain], "(");
left += ")"; // 此处用insert(pos, ")")会出错, 上面Insert之后后面部分整体移动, insert 到pos+1位置
break;
}
m[remain] = pos++;
left += to_string((remain*10)/down);
remain = (remain*10)%down;
}
if(left=="") return ret;
else return ret+"."+left;
}
};