const int shift = sizeof(int) * 8 - 1;
#define LESS_THAN_ZERO(X) (X)>>shift
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if(!denominator){
return "NaN";
}
string res = "";
if(numerator && denominator &&
(LESS_THAN_ZERO(numerator)) ^ (LESS_THAN_ZERO(denominator))){
res = "-";
}
int remainder = 0;
if(numerator == INT_MIN && abs(denominator) == 1)
{
res += to_string(INT_MIN);
res.erase(0,1);
}else{
res += to_string(abs(numerator / denominator));
remainder = abs(numerator % denominator);
}
if(remainder){
unordered_map<int,int> repeat;
res += ".";
const int FACTOR = (LESS_THAN_ZERO(denominator - 10)? 1 :10),
FACTOR_RECIPROCAL = 10 / FACTOR;
int digit = abs(denominator % FACTOR);
auto NEW_REMAINDER = [](int R,int r,int D,int d,int F) -> int{
return (F*R - r * d - r * D * F);
};
denominator = abs(denominator / FACTOR);
for(int curPos = res.length(); remainder; curPos++){
if(repeat.count(remainder)>0){
res.insert(repeat[remainder],"(");
res.push_back(')');
return res;
}
repeat[remainder]=curPos;
remainder = FACTOR_RECIPROCAL * remainder;
int tmpRes = remainder / denominator;
while(LESS_THAN_ZERO(
NEW_REMAINDER(remainder,tmpRes,denominator,digit,FACTOR)))
{
tmpRes--;
}
remainder = NEW_REMAINDER(remainder,tmpRes,denominator,digit,FACTOR);
res += to_string(tmpRes);
}
}
return res;
}
};
Leetcode (没有转换long long类型) Fraction to Recurring Decimal
最新推荐文章于 2023-01-04 12:01:58 发布