Member-only story
Solution to Leetcode problem 972 Equal Rational Numbers
In this problem, the authors introduce a common notation for rational numbers (with repeating decimals) and invite us to find out if two notations have the same value.
The solution to this type of problem is often to find a canonical way of representing the class of numbers that are equivalent. For instance, I know that 2/4 and 3/6 have the same value by reducing the reducing both fractions to the irreducible 1/2.
This is what I have done in the solution below. I followed a few rules to reduce the rational number to a canonical annotation, reduced both numbers and compared their reduced representation.
First I introduced the class Rational
, which is essentially the break down in 3 strings of the initial string representation of a rational number.
public class Rational {
public String integer;
public String nonRepeating;
public String repeating; public Rational(String s) {
if (s.indexOf('.') == -1) {
integer = s;
nonRepeating = "";
repeating = "";
} else {
int dotIndex = s.indexOf('.');
integer = s.substring(0, dotIndex);
if (s.indexOf('(') == -1) {
nonRepeating = s.substring(dotIndex + 1, s.length());
repeating = "";
} else {
int parIndex = s.indexOf('(')…