Fraction to recurring decimal

Source: Internet
Author: User

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.

Idea: Take 2/7 as an example:

Class solution {public: String to_string (long x) {STD: String number; STD: stringstream strstream; strstream <X; strstream> Number; return number ;} string fractiontodecimal (INT num, int den) {// although declared as int, if (num = 0) {return "0 ";} string Sign = ""; // The result symbol if (Num> 31) ^ (Den> 31 ))! = 0) {// Sign = "-";} long Numerator = ABS (long) num); // convert it to long, use ABS long Denominator = ABS (long) Den); If (numerator % Denominator = 0) {// return sign + to_string (numerator/denominator);} Long n = numerator/denominator; // The integer part Numerator = numerator % denominator; // molecular map <int, int> m; long I = 0; string S = ""; bool flag = false; while (M. find (numerator) = m. end () {M [numerator] = I; numerator * = 10; I ++; If (Numerator = 0) {// flag = true; break ;} if (numerator <denominator) {// fill in 0 S + = "0";} else {int L = numerator/denominator; S + = to_string (L ); numerator % = Denominator;} If (FLAG) {return sign + to_string (n) + ". "+ S;} int Index = m. find (numerator)-> second; return sign + to_string (n) + (". "+ S. substr (0, index) + "(" + S. substr (index, I-index) + ")";}};

Fraction to recurring decimal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.