166. 分数到小数
给定两个整数,分别表示分数的分子 numerator
和分母 denominator
,以 字符串形式返回小数 。
如果小数部分为循环小数,则将循环的部分括在括号内。
如果存在多个答案,只需返回 任意一个 。
对于所有给定的输入,保证 答案字符串的长度小于 104
。
示例 1:
输入:numerator = 1, denominator = 2 输出:"0.5"
示例 2:
输入:numerator = 2, denominator = 1 输出:"2"
示例 3:
输入:numerator = 4, denominator = 333 输出:"0.(012)"
提示:
-231 <= numerator, denominator <= 231 - 1
denominator != 0
解析:
这题牛!
用竖式除法来做,模拟竖式即可
坑太多,呜呜呜呜,难过
class Solution { public: int caldigit(long long quotient) { if(quotient == 0) return 2; int ret = 0; while(quotient) { ret++; quotient /= 10; } return ++ret; } string fractionToDecimal(int numerator, int denominator) { if(numerator == 0) return "0"; int flag1 = 1; long long num, den; if(numerator < 0) flag1 = -flag1, num = numerator, num = -num; else num = numerator; if(denominator < 0) flag1 = -flag1, den = denominator, den = -den; else den = denominator; unordered_map<long long, int> hashmap; long long remainder = num; string ret = ""; long long quotient = remainder / den; ret += to_string(quotient); remainder %= den; if(remainder == 0) return flag1 == -1 ? "-" + ret : ret; ret += '.'; int cnt = caldigit(quotient); while(remainder) { hashmap[remainder] = cnt++; remainder *= 10; while(remainder < den) { hashmap[remainder] = cnt++; remainder *= 10; ret += '0'; } quotient = remainder / den; ret += to_string(quotient); remainder %= den; int x = hashmap[remainder]; if(x) { ret += ')'; ret += 'a'; int i; for(i = ret.size() - 2; i >= x; i--) ret[i + 1] = ret[i]; ret[i + 1] = '('; return flag1 == -1 ? "-" + ret : ret; } } return flag1 == -1 ? "-" + ret : ret; } };