[LeetCode] Fraction to Recurring Decimal 哈希表
2015-03-31 21:13
323 查看
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)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
Hide Tags
Hash Table Math
题目其实挺容易的,需要考虑的是溢出问题,long int 长度是32 位的, long long int 才是64位。
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)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
Hide Tags
Hash Table Math
题目其实挺容易的,需要考虑的是溢出问题,long int 长度是32 位的, long long int 才是64位。
#include <iostream> #include <unordered_map> #include <string> #include <sstream> using namespace std; class Solution { public: string fractionToDecimal(int numerator, int denominator) { bool flag1 = numerator<0; bool flag2 = denominator<0; unsigned numer = flag1?-numerator:numerator; unsigned denom = flag2?-denominator:denominator; if(denom==0) return ""; if(numer==0) return "0"; stringstream ss; ss<<numer/denom; string ret = ss.str(); unsigned long long int lft = numer%denom; unordered_map<unsigned int,unsigned int> mp; string ret1=""; unsigned int cnt = 1; while(lft){ if(mp[lft]==0){ mp[lft]=cnt++; ret1 += (lft*10)/denom + '0'; lft = (lft*10)%denom; continue; } ret1 = ret1.substr(0,mp[lft]-1) + "(" + ret1.substr(mp[lft]-1) + ")"; break; } if(ret1 != "") ret += "." + ret1; if(flag1^flag2) ret = "-" + ret; return ret; } }; int main() { Solution sol; cout<<sol.fractionToDecimal(-1,-2147483648)<<endl; return 0; }
相关文章推荐
- 【leetcode 哈希表】Fraction to Recurring Decimal
- leetcode Fraction to Recurring Decimal 哈希表
- LeetCode Fraction to Recurring Decimal
- leetcode 日经贴,Cpp code -Fraction to Recurring Decimal
- [leetcode] Fraction to Recurring Decimal
- Leetcode|Fraction to Recurring Decimal
- Leetcode#166 Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- LeetCode之Fraction to Recurring Decimal
- [Leetcode]166. Fraction to Recurring Decimal @python
- [leetcode 166] Fraction to Recurring Decimal
- [leetcode] Fraction to Recurring Decimal
- LeetCode 166 Fraction to Recurring Decimal
- leetcode——166—— Fraction to Recurring Decimal
- LeetCode(166) Fraction to Recurring Decimal
- leetcode_c++:哈希:Fraction to Recurring Decimal(166)
- LeetCode-Fraction to Recurring Decimal-解题报告
- [LeetCode#116]Fraction to Recurring Decimal
- [leetCode] Fraction to Recurring Decimal
- LeetCode 166 Fraction to Recurring Decimal (从分数到循环小数)(*)