题目来源
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.
For example,
- Given numerator = 1, denominator = 2, return "0.5".
- Given numerator = 2, denominator = 1, return "2".
- Given numerator = 2, denominator = 3, return "0.(6)".
怎么把分数写成循环小数的形式?想着先把整数求出来吧,假设分子是a
,分母是b
,那么整数部分就是a/b
,然后判断a%b
是不是为0,不是的话怎么办呢?好好想一想!
思考中
¥%……@%¥@¥¥#……@#¥%@¥¥%@#¥%%¥#……#¥%
然后判断是不是可以除尽,可以除尽的话直接输出,不能除尽的话找循环部分。怎么找循环部分呢?想不出来了…
好吧,我又看了大神们的做法,想想我们平时做除法是怎么做的,比如2除以3,2除以3余2,补0再除,余2,发现余数重复了,那么之后就会一直循环下去了对不对,对不对对不对!对啊,卧槽没想到啊,我个笨脑子!
然后一开始还得注意考虑下正负问题,考虑除数是0的问题,还得考虑除数或被除数是INT_MIN的问题,所以得把类型定义为long long
。
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
string res = "";
if (numerator == 0)
return "0";
if (numerator < 0 ^ denominator < 0)
res += "-";
long long n = abs((long long)(numerator));
long long d = abs((long long)(denominator));
long long z = n / d;
res += to_string(z);
if (n % d == 0)
return res;
else {
unordered_map<int, int> map;
res += ".";
for (long long r = n % d; r; r = r % d) {
if (map[r] > 0) {
res.insert(map[r], 1, '(');
res += ")";
break;
}
map[r] = res.size();
r *= 10;
res += char(r / d + 48);
}
}
return res;
}
};