Leetcode-Fraction to Recurring Decimal
2015-03-09 19:09 欧陈庚 阅读(297) 评论(0) 编辑 收藏 举报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)"
题目链接 https://leetcode.com/problems/fraction-to-recurring-decimal/
题目的意思其实很简单,给一个除数和被除数,返回商,只不过如果有循环的部分,用括号括起来。
题目本来很简单,一直做除法直到碰到重复出现的余数为止(每次除的时候,把被除数扩大十倍,相当于小数点向后移一位),用一个hashmap来记录余数的出现。
但是,测试用例真心碉堡了。会出现(INT_MIN)/(-1)这样的测试case,因为INT_MIN的绝对值比INT_MAX要大1,所以即使输入的都是int,但是中间结果很可能越界。所以需要使用long long。
有个小技巧,在构造返回值的时候,用ostringstream比直接用string来进行加减,会有效率得多。
//Fraction to Recurring Decimal string fractionToDecimal(int numerator1, int denominator1){ long long numerator = (long long)(numerator1); long long denominator = (long long)(denominator1); ostringstream os; if(numerator * denominator < 0) os<<"-"; numerator = numerator > 0 ? numerator : (-numerator); denominator = denominator > 0 ? denominator : (-denominator); long long zhengshu = numerator / denominator; long long remains = numerator - zhengshu * denominator; os<<zhengshu; if(remains == 0) return os.str(); int shang; vector<int> ans; int counter = 0; int flag = false; map<long long, int> pos; map<long long, int>::iterator it; int position; while(remains != 0) { remains *= 10; it = pos.find(remains); if(it != pos.end()) { position = it->second; flag = true; break; } shang = remains / denominator; ans.push_back(shang); pos.insert(make_pair(remains, counter++)); remains = (remains) - (shang * denominator); } os<<"."; for(int i = 0; i < ans.size(); i++) { if(i == position && flag) os<<"("; os<<ans[i]; } if(flag) os<<")"; return os.str(); }