166. Fraction to recurring Decimal

Source: Internet
Author: User

Given integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part was 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) ".

Hint:

    1. No scary Math, just apply elementary math knowledge. Still remember how to perform a long division?
    2. Try a long division on 4/9, and the repeating part is obvious. Now try 4/333. Do you see a pattern?
    3. Be wary of Edge cases! List out as many test cases as can think of and test your code thoroughly.

 Public classSolution { PublicString Fractiontodecimal (intNumerator,intdenominator) {        if(Numerator = = 0) {            return"0"; } StringBuilder Res=NewStringBuilder (); //"+" or "-"Res.append (((Numerator > 0) ^ (Denominator > 0))? "-" : ""); Longnum = Math.Abs (Long) numerator); LongDen = Math.Abs ((Long) denominator); //Integral partRes.append (num/den); Num%=den; if(num = = 0) {            returnres.tostring (); }        //Fractional partRes.append ("."); HashMap<long, integer> map =NewHashmap<long, integer>();        Map.put (num, res.length ());  while(num! = 0) {num*= 10; Res.append (Num/den); Num%=den; if(Map.containskey (num)) {intindex =map.get (num); Res.insert (Index,"("); Res.append (")");  Break; }            Else{map.put (num, res.length ()); }        }        returnres.tostring (); }}

166. 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.