Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Fraction to Recurring Decimal in C++
Suppose we have two integers representing the numerator and denominator of a fraction, we have to find fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. So if the numerator is 2 and denominator is 3, then the output will be “0.(6)”
To solve this, we will follow these steps −
if numerator is 0, then return 0
define one array ans
if the numerator < 0 and denominator > 0 or numerator 0 and denominator < 0, then insert negative symbol ‘-’ into the ans array
divisor := |numerator| and dividend := |denominator|, remainder := divisor mod dividend
x := string of divisor / dividend
insert each character from x into ans array
if remainder = 0, then return ans array as a string.
insert dot ‘.’ into ans
define one map m
-
while remainder is not 0
-
if remainder is present in m, then
insert opening parentheses at index m[remainder] of ans
insert closing parentheses into the ans at the end
break the loop
-
otherwise
m[remainder] := size of ans
remainder := remainder * 10
insert (remainder / dividend) as character into ans
remainder := remainder mod dividend
-
return ans array as string.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if(numerator == 0)return "0";
vector <char> ans;
if(numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0)ans.push_back('-');
long divisor = labs(numerator);
long dividend = labs(denominator);
long remainder = divisor % dividend;
string x = to_string(divisor/dividend);
for(int i = 0; i < x.size(); i++){
ans.push_back(x[i]);
}
if(remainder == 0){
return string(ans.begin(), ans.end());
}
ans.push_back('.');
map <int, int> m;
while(remainder != 0){
if(m.find(remainder)!=m.end()){
ans.insert(ans.begin() + m[remainder], '(');
ans.push_back(')');
break;
}else{
m[remainder] = ans.size();
remainder *= 10;
ans.push_back((remainder / dividend) + '0');
remainder %= dividend;
}
}
return string(ans.begin(), ans.end());
}
};
main(){
Solution ob;
cout << ((ob.fractionToDecimal(100,6)));
}
Input
100 6
Output
16.(6)