# Equal Rational Numbers in C++

Suppose we have two strings, these are S and T, each of which represents a positive rational number, We have to check whether they represent the same number or now. The strings may use parentheses to denote the repeating part of the rational number.

As we know that rational numbers can be represented using up to three parts: an integer part, a non-repeating part, and a repeating part. The number will be represented in one of the following three ways −

• Only integer part (like 0, 12, 123)

• IntegerPart.NonRepeatingPart (like 0.5, 1.0, 2.12, 2.0001)

• IntegerPart.NonRepeatingPart(RepeatingPart>) (like 0.1(6), 0.9(9), 0.00(1212))

For example Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.

So, if the input is like S = "0.(52)" and T = "0.5(25)", then the output will be True.

To solve this, we will follow these steps −

• Define a function f(), this will take S,

• i := index of '(' in S

• if i is in range of S lenght, then −

• base := substring of S from index 0 to i - 1

• rep := substring of S from index i + 1 to (length of S - i - 3)

• for initialize j := 0, when j < 20, update (increase j by 1), do −

• base := base + rep

• return base as real value

• return S as real value

• From the main function do the following −

• return true when f(S) is same as f(T)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;class Solution {
public:
bool isRationalEqual(string S, string T){
return f(S) == f(T);
}
double f(string S){
auto i = S.find("(");
if (i != string::npos) {
string base = S.substr(0, i);
string rep = S.substr(i + 1, S.length() - i - 2);
for (int j = 0; j < 20; ++j)
base += rep;
return stod(base);
}
return stod(S);
}
};
main(){
Solution ob;
cout << (ob.isRationalEqual("0.(52)", "0.5(25)"));
}

## Input

"0.(52)", "0.5(25)"

## Output

1