Fraction to Recurring Decimal


Problem Statement :


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.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

 

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:

Input: numerator = 2, denominator = 1
Output: "2"
Example 3:

Input: numerator = 4, denominator = 333
Output: "0.(012)"
 

Constraints:

-231 <= numerator, denominator <= 231 - 1
denominator != 0



Solution :



title-img


                            Solution in C :

long abs1(long a){
    return a < 0 ? -a : a;
}

long repIndex(long* arr, long len, long num){
    for(int i = 0; i < len; i++){
        if(arr[i] == num)
            return i;
    }
    return -1;
}

int length(int num){
    int len = num == 0 ? 1 : 0;
    while(num != 0){
        num /= 10;
        len ++;
    }
    return len;
}

char * fractionToDecimal(int numerator, int denominator){   //Assume: 1  6  Result: 0.1(6)
    long num = numerator, den = denominator;                //cast to long                    
    long integer = num / den;  //0
    
    int sign = 0;
    int iLen = length(integer);                             //1
    
    // Set positive for all
    if((long)num * den < 0){
        sign = 1;
        integer = -integer;
        num = abs1(num);
        den = abs1(den);
    }
    
//=========================================================================================
    bool repeat = 0;
    int fLen = 0, index = -1;                               //fLen: Fraction length, index: repeat at index (0.16666 -> index = 1)
    if(num % den){                                          //mod is not 0
        fLen ++;                                            //if mod is not 0, it has dot.
        int maxUnrepeated = length(den) + 1 /*2*/, realUnrepeated = 0;
        long *mods = malloc(maxUnrepeated * sizeof(long));  //Store unrepeated mods * 10. In the case of 1/6, it would be 1 * 10 and 4 * 10.
        long n = num % den * 10;                            //0.16666 -> n = 10
        do{
            if(realUnrepeated < maxUnrepeated){
                mods[realUnrepeated] = n;
                realUnrepeated ++;
            }
            fLen ++;
            n = n % den * 10;
            index = repIndex(mods, realUnrepeated, n);      //0.16666 -> index = 1
            if(index != -1){                                //if index != -1, n is found in mods[] 
                repeat = 1;
                fLen += 2;                                  //()
                break;
            }
        }while(n);
    }
//=========================================================================================
    int len = sign + iLen + fLen;                           //0.1(6) -> 0 + 1 + 5
    char* r = malloc((len + 1) * sizeof(char)), *p = r;

    //copy sign
    if(sign) *p++ = '-';
    
    //copy integer
    for(int i = iLen - 1; i >= 0; i--){
        p[i] = (integer % 10) + '0';
        integer /= 10;
    }
    
    if(fLen){
        p += iLen;                                         //move the pointer to the fractional part
        *p++ = '.';
    }

    if(repeat){
        p[index] = '(';
        r[len - 1] = ')';
        fLen -= 3;
    }
    
    //copy fraction
    long n = num, mod;
    for(int i = 0; i < fLen; i++){
        mod = n % den; //4
        n = mod * 10;
        if(p[i]=='(')p++;
        p[i] = n / den + '0';
    }
    
    r[len] = '\0';
    return r;
}
                        


                        Solution in C++ :

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(numerator == 0){
            return  "0";
        }
        
        StringBuilder sb = new StringBuilder("");
        if(numerator<0 && denominator>0 || numerator>0 && denominator<0){
            sb.append("-");
        }
        
        long divisor = Math.abs((long)numerator);
        long dividend = Math.abs((long)denominator);
        long remainder = divisor % dividend;
        sb.append(divisor / dividend);
        
        if(remainder == 0){
            return sb.toString();
        }
        sb.append(".");
        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        while(remainder!=0){
            if(map.containsKey(remainder)){
                sb.insert(map.get(remainder), "(");
                sb.append(")");
                break;
            }
            map.put(remainder, sb.length());
            remainder*= 10;
            sb.append(remainder/dividend);
            remainder%= dividend;
        }
        return sb.toString();
    }
}
                    


                        Solution in Java :

class Solution {
    StringBuilder sb;
    public String fractionToDecimal(int numerator, int denominator) {

        if(numerator == 0){
            return "0";
        }   
        sb = new StringBuilder();
        
        addSign(numerator,denominator);
        divideNumbers(numerator,denominator);

        return sb.toString();
    }
    private void addSign(int a , int b){
        
        if((a > 0 && b > 0) || (a < 0 && b < 0)){
            return;
        }    
        sb.append("-");
    }
    private void divideNumbers(int a,int b){
        
        long num = Math.abs((long)a);
        long den = Math.abs((long)b);

        sb.append(num/den);
        num %= den;
        if(num == 0){
            return;
        } 
        appendDecimalPart(num,den);
    }
    private void appendDecimalPart(long num, long den){

        HashMap<Long,Integer> map = new HashMap<>();
        sb.append(".");
        while(num !=0){

            num *= 10;
            sb.append(num/den);
            num %= den;

            if(map.containsKey(num)){
                sb.insert(map.get(num),"(");
                sb.append(")");
                return;
            }
            else{
                map.put(num,sb.length());
            }
        }
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        # Handle edge cases
        if numerator == 0:
            return "0"
        if denominator == 0:
            return ""

        # Initialize result and check for negative sign
        result = ""
        if (numerator < 0) ^ (denominator < 0):
            result += "-"
        numerator, denominator = abs(numerator), abs(denominator)

        # Integer part of the result
        result += str(numerator // denominator)

        # Check if there is a fractional part
        if numerator % denominator == 0:
            return result

        result += "."

        # Use a dictionary to store the position of each remainder
        remainder_dict = {}
        remainder = numerator % denominator

        # Keep adding the remainder to the result until it repeats or the remainder becomes 0
        while remainder != 0 and remainder not in remainder_dict:
            remainder_dict[remainder] = len(result)
            remainder *= 10
            result += str(remainder // denominator)
            remainder %= denominator

        # Check if there is a repeating part
        if remainder in remainder_dict:
            result = result[:remainder_dict[remainder]] + "(" + result[remainder_dict[remainder]:] + ")"

        return result
                    


View More Similar Problems

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →