首页 > 代码库 > LeetCode Fraction to Recurring Decimal
LeetCode Fraction to Recurring Decimal
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)".
Solution:
1 string fractionToDecimal(int numerator, int denominator) { 2 int neg = 0; 3 int flag = 0; 4 int recurring = 1; 5 if ((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0)) neg = 1; 6 unsigned long long num = (numerator == -2147483648)? 2147483648 : abs(numerator); 7 unsigned long long den = (denominator == -2147483648)? 2147483648 : abs(denominator); 8 9 unsigned long long integer = num / den;10 unsigned long long remain = num % den;11 flag = (remain == 0 ? 1 : 0);12 13 map<int, int> seen;14 seen[remain] = 0;15 vector<int> digits;16 while (1) {17 remain *= 10;18 digits.push_back(remain / den);19 remain = remain % den;20 recurring = (remain == 0) ? 0 : 1;21 if (seen.count(remain)) {22 int where = seen[remain];23 ostringstream os;24 if (neg) {25 os << ‘-‘;26 }27 os << integer;28 if (!flag) {29 os << ‘.‘;30 for (int i = 0; i < where; ++i)31 {32 os << digits[i];33 }34 if (recurring)35 {36 os << ‘(‘;37 for (int i = where; i < digits.size(); ++i) 38 os << digits[i];39 os <<‘)‘;40 }41 42 }43 44 return os.str();45 }46 else 47 seen[remain] = digits.size();48 49 }50 51 }
LeetCode Fraction to Recurring Decimal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。