[LeetCode] Fraction to Recurring Decimal

Source: Internet
Author: User

[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 )".


    This problem is still difficult to implement. We need to consider the input of negative numbers, especially the Boundary Value of the integer type-2147483648. The simplest way is to convert all input values to positive numbers of long integers.

    In addition, because we want to record the cyclic part of the decimal point, we also need to use a Map to record each decimal point and the corresponding remainder value. If the same remainder value is met, it indicates that the part of the Start loop is encountered.

    public String fractionToDecimal(int numerator, int denominator) {long longNumerator = Math.abs((long) numerator);long longDenominator = Math.abs((long) denominator);StringBuilder sb = new StringBuilder();if ((long) numerator * denominator < 0) sb.append("-");sb.append(longNumerator / longDenominator);long remainder = longNumerator % longDenominator;if (remainder == 0) return sb.toString();sb.append(".");StringBuilder fracSb = new StringBuilder();Map
       
         map = new HashMap
        
         ();int index = 0;while (remainder != 0) {remainder *= 10;long nextRemainder = remainder % longDenominator;// If repeated part occurs.if (map.containsKey(remainder)) {fracSb.insert(map.get(remainder), "(");fracSb.append(")");break;}map.put(remainder, index++);fracSb.append(remainder / longDenominator);remainder = nextRemainder;}sb.append(fracSb);return sb.toString();}
        
       


Related Article

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.