"Leetcode" fraction to recurring Decimal "solution"

Source: Internet
Author: User
Tags time 0

Topic

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) ".
Test instructions

Returns the decimal number as a string, given a numerator and a denominator. If the decimal infinite loop, enclose the loop body with parentheses.


"Official Solution"

    0.16   6) 1.00   0    1 0       <--remainder=1, Mark 1 as seen at position=0.    -6      <--remainder=4, Mark 4 as seen at Position=1.    -       4      <--remainder=4 was seen before at Position=1, so the fractional part which is starts rep Eating at position=1 = 1 (6).

The key insight here's to notice this once the remainder starts repeating, so does the divided result.

You'll need a hash table, the maps from the remainder to their position of the fractional part. Once found a repeating remainder, you may enclose the reoccurring fractional part with parentheses by consulting the P Osition from the table.

The remainder could is zero while doing the division. That means there was no repeating fractional part and you should stop right away.

Just like the question Divide-integers, be-wary of edge case such as negative fractions and nasty extreme case such as -2147483648 / -1.


"Chinese Interpretation"

Difficulty : How to identify the loop body?

workaround : Record each remainder with a hashmap, and when there is a duplicate remainder, it will enter the loop, and the part between the two repeating remainder is the loop body.

example : 1/13=0. 076923076923076923..., when the decimal part appears for the second time 0 o'clock, which means that the loop is started, you need to enclose 076923 in parentheses, and the result is 0. (076923).

techniques involved : 1) in the process of continuous division, the remainder multiplied by 10 and then the next division, the guarantee is always divided into integers, 2) HashMap key and value are < The current remainder, the corresponding result subscript; This allows for 076923 to be found based on value.

Note 1: Consider positive negative numbers, first judge the symbols, and then all converted to positive numbers;

Note Point 2: Consider overflow, if the input is Integer.min_value, the absolute value will overflow.

Comments have been added to the code to see the code:

public class Solution {public String fractiontodecimal (int numerator, int denominator) {if (numerator = = 0) re        Turn "0";                if (denominator = = 0) return "";                String ans = "";        If the result is negative if ((Numerator < 0) ^ (Denominator < 0)) {ans + = "-";        }//To convert two numbers to positive, to avoid overflow, int to long long num = numerator, den = denominator;        num = Math.Abs (num);                Den = Math.Abs (DEN);        The integer part of the result, long res = Num/den;                Ans + = string.valueof (res);        If divisible, returns the result long rem = (num% den) * 10;                if (rem = = 0) return ans;        The results of the decimal part of the Hashmap<long, integer> map = new Hashmap<long, integer> ();        Ans + = "."; while (REM! = 0) {//If the remainder has already appeared before, then the loop will start if (Map.containskey (REM)) {int beg = map. Get (REM);                The starting position of the loop body String part1 = ans.substring (0, Beg); String Part2 = ans.substring (Beg, Ans.length ());                Ans = part1 + "(" + Part2 + ")";            return ans;            }//Continue to remove Map.put (REM, ans.length ());            res = Rem/den;            Ans + = string.valueof (res);        rem = (rem% den) * 10;    } return ans; }}

Java programming Myth : Be sure to first convert int to long, and then take the absolute value. If a long num = Math.Abs (numerator) is a problem, because this code is equivalent to long num = Math.Abs (-2147483648) at Numerator=integer.min_value, the resulting Num is still-2147483648.


Reference source 1:http://www.cnblogs.com/ganganloveu/p/4170601.html

Reference source 2:https://oj.leetcode.com/discuss/18780/my-java-solution-with-explanation-second-version


"Leetcode" fraction to recurring Decimal "solution"

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.