A Simple Fraction | Practice | GeeksforGeeks

Given a fraction. Convert it into a decimal. 
If the fractional part is repeating, enclose the repeating part in parentheses.
 
Example 1:
Input: numerator = 1, denominator = 3
Output: "0.(3)"
Explanation: 1/3 = 0.3333... So here 3 is 
recurring.

Example 2:
Input: numerator = 5, denominator = 2
Output: "2.5"
Explanation: 5/2 = 2.5

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function fractionToDecimal() which takes numerator and denominator as input parameter and returns its decimal form in string format.
Note: In case, the numerator is divisible by the denominator, just print the integer value.
 
Expected Time Compelxity: O(k) where k is constant.
Expected Space Complexity: O(k)
 
Constraints:
1 ≤ numerator, denominator ≤ 2000
+1
sujoykarmakar3212 months ago
string fractionToDecimal(int nu, int de) { 
 string s="";   
 unordered_map<int,int>mp; 
 int w=nu/de; 
 int re=nu%de;  
 s+=to_string(w);  
 if(re==0) return s;  
 s.push_back('.');  
 int pos=s.size();  
 while (re){   
   re*=10; 
   int x=re/de;
   if(mp[re]){
      s.insert(mp[re],"(");  
      break; 
    } 
    mp[re]=pos; 
    re=re%de; 
    s+=to_string(x); 
    if(re==0) return s;  
    pos++; 
 } 
 s.push_back(')'); 
 return s;
}
 
-1
abhinavsinghbiz2 months ago
C++ Code,O(K),O(K),Run Time=0.0
 
This que is solved by using Hashing and the concept of maps!
So if you do not know these please do not waste your time on this!
 
string fractionToDecimal(int n, int d) {    string ans;    int q=floor(n/d);    int r=n%d;    ans+=to_string(q);    if(r==0){        return ans;        }    ans+=".";        map<int,int>mp;    while(r!=0){    if(mp.find(r)!=mp.end()){           int len=mp[r];           ans.insert(len,"(");           ans+=")";           return ans;    }    else{        mp.insert(pair<int,int>(r,ans.length()));        r*=10;        q=floor(r/d);        r%=d;        ans+=to_string(q);    }    }}
0
eeshanatri29042 months ago
string fractionToDecimal(int numerator, int denominator) {
	    int whole=numerator/denominator;
	    int decimal=numerator % denominator;
	    string ans=to_string(whole);
	    if (decimal==0) return ans;
	    unordered_map<int,int> mp;
	    mp.clear();
	    ans+=".";
	    while (decimal!=0)
	    {
            if (mp.count(decimal))	       
            {
                ans.insert(mp[decimal],"(");
                ans+=")";
                return ans;
            }
            else 
            {
                mp[decimal]=ans.length();
                decimal*=10;
                int q=decimal/denominator;
                decimal=decimal % denominator;
                ans+=to_string(q);
            }
	    }
	    return ans;
	}
0
pratyushprasar3 months ago
In Javascript
class Solution {
    fractionToDecimal(numerator,denominator){
        //code here
        let res = numerator/ denominator;
        let rem = numerator%denominator;
        
        let arr = [];
        
        arr.push(String(parseInt(numerator/ denominator)));
        
        
        if(rem===0) return String(res);
        arr.push(".");
        
        let obj = new Object();
        
        while(rem!==0){
            if(obj.hasOwnProperty(rem)){
                arr.splice(obj[rem],0,"(");
                arr.push(")");
                break;
            }
         
         
         obj[rem]=arr.length;
         rem*=10;
         arr.push(String(parseInt(rem/ denominator)))
         rem%=denominator
           
        }
        
        return arr.join("")
           
           
    }
}
0
nikhilbisen25
This comment was deleted.
+1
thegitesh3 months ago
class Solution{public:string fractionToDecimal(int numerator, int denominator) {    // Code here       string ans = "";       int q = numerator/denominator;       int rem = numerator%denominator;       ans = to_string(q);       if (rem == 0)       {           return ans;       }       else       {           ans += ".";           unordered_map <int, int> map;           map.clear();                      while (rem != 0)           {               if (map.find(rem) != map.end())               {                   ans.insert(map[rem],"(");                   ans.append(")");                   break;               }               else                {                   map[rem] = ans.length();                   rem *= 10;                   q = rem/denominator;                   rem = rem%denominator;                   ans.append(to_string(q));               }           }           return ans;       }       }};
0
immortalsuv4 months ago
string fractionToDecimal(int numerator, int denominator) {
    // Code here
    string ans;
    int q = numerator/denominator;
    ans = to_string(q);
    int r = numerator%denominator;
    if(r==0){
        return ans;
    }
    else{
        ans+='.';
        unordered_map<int,int> rwp; // remainder along with position when they occured
        while(r!=0){
            if(rwp.count(r)){
                ans.insert(rwp[r],"(");
                ans+=')';
                return ans;
            }
            rwp[r]=ans.length();
            r*=10;
            q = r/denominator;
            ans+=to_string(q);
            r%=denominator;
        }
    }
}
0
bharatsinghkushwah10007 months ago
i am having sigbart error
0
insanebanda7 months ago
Also accepted on Leetcode:)
 
class Solution {   public String fractionToDecimal(long numerator, long denominator) {              if (numerator == 0) {           return "0";       }              long n = Math.abs(numerator);       long d = Math.abs(denominator);              StringBuilder res = new StringBuilder(numerator < 0 ^ denominator < 0 ? "-" : "");       res.append(n / d);              if (n % d == 0) {           return res.toString();       }              n %= d;       res.append(".");       HashMap<Long, Integer> remainders = new HashMap<>();       remainders.put(n, res.length());              while (n != 0) {           n *= 10;           res.append(n / d);           n %= d;           if (remainders.containsKey(n)) {               int index = remainders.get(n);               res.insert(index, "(");               res.append(")");               break;           } else {               remainders.put(n, res.length());           }       }              return res.toString();   }}
0
mrudul1203
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.