You are given a string str containing two fractions a/b and c/d, compare them and return the greater. If they are equal, then return “equal“.
Note: The string str contains “a/b, c/d“(fractions are separated by comma(,) & space( )).
Examples
Input: str = "5/6, 11/45" Output: 5/6 Explanation: 5/6=0.8333 and 11/45=0.2444, So 5/6 is greater fraction.
Input: str = "8/1, 8/1" Output: equal Explanation: We can see that both the fractions are same, so we'll return a string "equal".
Input: str = "10/17, 9/10" Output: 9/10 Explanation: 10/17 = 0.588 & 9/10 = 0.9, so the greater fraction is "9/10".
Expected Time Complexity: O(len|str|)
Expected Auxiliary Space: O(1)
Constraints:
0<=a,c<=103
1<=b,d<=103
Approach 01:
-
C++
-
Python
#include <iostream> #include <string> using namespace std; class Solution { public: string compareFrac(string s) { // Find the position of the comma in the input string const size_t pos = s.find(','); // Separate the input string into two substrings, one for each fraction string s1 = s.substr(0, pos); // First fraction string s2 = s.substr(pos + 2); // Second fraction (skip ", ") // Calculate the cross-multiplication values to compare the fractions int l = stoi(s1) * stoi(s2.substr(s2.find('/') + 1)); // a * d int r = stoi(s2) * stoi(s1.substr(s1.find('/') + 1)); // c * b // Compare the cross-multiplication values and return the appropriate result return l == r ? "equal" : l > r ? s1 : s2; } };
class Solution: def compareFrac(self, s: str) -> str: # Find the position of the comma in the input string pos = s.find(',') # Separate the input string into two substrings, one for each fraction s1 = s[:pos].strip() # First fraction s2 = s[pos + 2:].strip() # Second fraction (skip ", ") # Calculate the cross-multiplication values to compare the fractions l = int(s1.split('/')[0]) * int(s2.split('/')[1]) # a * d r = int(s2.split('/')[0]) * int(s1.split('/')[1]) # c * b # Compare the cross-multiplication values and return the appropriate result if l == r: return "equal" elif l > r: return s1 else: return s2