Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.html
If the fractional part is repeating, enclose the repeating part in parentheses.post
For example,this
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.url
這道題仍是比較有意思的,開始還擔憂萬一結果是無限不循環小數怎麼辦,百度以後才發現原來能夠寫成分數的都是有理數,而有理數要麼是有限的,要麼是無限循環小數,無限不循環的叫無理數,例如圓周率pi或天然數e等,小學數學沒學好,汗!因爲還存在正負狀況,處理方式是按正數處理,符號最後在判斷,那麼咱們須要把除數和被除數取絕對值,那麼問題就來了:因爲整型數INT的取值範圍是-2147483648~2147483647,而對-2147483648取絕對值就會超出範圍,因此咱們須要先轉爲long long型再取絕對值。那麼怎麼樣找循環呢,確定是再獲得一個數字後要看看以前有沒有出現這個數。爲了節省搜索時間,咱們採用哈希表來存數每一個小數位上的數字。還有一個小技巧,因爲咱們要算出小數每一位,採起的方法是每次把餘數乘10,再除以除數,獲得的商即爲小數的下一位數字。等到新算出來的數字在以前出現過,則在循環開始出加左括號,結束處加右括號。代碼以下:spa
class Solution { public: string fractionToDecimal(int numerator, int denominator) { int s1 = numerator >= 0 ? 1 : -1; int s2 = denominator >= 0 ? 1 : -1; long long num = abs( (long long)numerator ); long long den = abs( (long long)denominator ); long long out = num / den; long long rem = num % den; unordered_map<long long, int> m; string res = to_string(out); if (s1 * s2 == -1 && (out > 0 || rem > 0)) res = "-" + res; if (rem == 0) return res; res += "."; string s = ""; int pos = 0; while (rem != 0) { if (m.find(rem) != m.end()) { s.insert(m[rem], "("); s += ")"; return res + s; } m[rem] = pos; s += to_string((rem * 10) / den); rem = (rem * 10) % den; ++pos; } return res + s; } };