Q-37* Fraction to Recurring Decimal - LeetCode

PHOTO EMBED

Fri Jan 27 2023 14:25:33 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    
    public String fractionToDecimal(int numerator, int denominator) {
        if(numerator == 0) return "0";

        //make variables 
        long q = 0 , rem = 0 ; // quotient and remainder
        StringBuilder ans = new StringBuilder();

    //store absolute values of numerator and denominator , negatives will be dealt later
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);
        
        boolean neg = false; // to check if ans should be negative or +ve
        if(numerator<0 || denominator<0) neg = true;

        if(numerator<0 && denominator<0) neg = false;

        
        //HM to store remainder and index position of string to check if rem is repeated
        //and add brackets at index position and at the end of the string;

        HashMap<Long,Long> map = new HashMap<>();
        q = num / den;
        rem = num % den;
        ans.append(q);

        if(rem == 0){

            if(neg)
            ans.insert(0,"-");

            return ans.toString();
        }
        

        else{
            ans.append("."); //adding decimal
            while(rem!= 0){
                
                if( map.containsKey(rem)){
                    long pos = map.get(rem);
                    ans.insert((int)pos,"(");
                    ans.append(")");
                    break;
                }
                
                else{
                    map.put(rem ,(long)ans.length());
                    rem *= 10;
                    
                    q = rem / den;
                    rem = rem % den;
                    ans.append(q);
                }
            }
        }

        if(neg)
            ans.insert(0,"-");
            
            return ans.toString();
    }
}









content_copyCOPY

https://leetcode.com/problems/fraction-to-recurring-decimal/